iOS 导航栏自定义 TitleView不居中的问题
来源:互联网 发布:淘宝上的伊皇是真的吗 编辑:程序博客网 时间:2024/06/06 03:21
#import "LTNavTitleView.h"@implementation LTNavTitleView{ UILabel *dateLabel; UILabel *infoLabel;}/*// Only override drawRect: if you perform custom drawing.// An empty implementation adversely affects performance during animation.- (void)drawRect:(CGRect)rect { // Drawing code}*/- (void)dealloc{}- (id)initWithFrame:(CGRect)frame{ if (self = [super initWithFrame:frame]) { [self initSubViews]; } return self;}- (void)initSubViews{ self.backgroundColor = [UIColor clearColor]; dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.frame.origin.y, self.frame.size.width, 20)]; dateLabel.backgroundColor = [UIColor clearColor]; dateLabel.textAlignment = NSTextAlignmentCenter; dateLabel.font = LT_FONT(16); dateLabel.textColor = [UIColor whiteColor]; [self addSubview:dateLabel]; infoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, dateLabel.frame.size.height, self.frame.size.width, 10)]; infoLabel.backgroundColor = [UIColor clearColor]; infoLabel.textAlignment = NSTextAlignmentCenter; infoLabel.font = LT_FONT(12); infoLabel.textColor = [UIColor whiteColor]; [self addSubview:infoLabel]; self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin; infoLabel.autoresizingMask = dateLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin ;}- (void)setDate:(NSString *)dateString{ dateLabel.text = dateString;}- (void)setInfo:(NSString *)infoString{ infoLabel.text = infoString;}然后用这个NavView来初始化 并赋值到titleView就行了,NavTitleView的初始化宽度要小于SCREEN的宽 减去leftBarButtonItem+rightBarButtonItem的宽度。,如果只有leftBarButtonItem或rightBarButtonItem一个宽度,则就用SCREEN的宽 减去这个barbutton的宽度x2这要注意 设置autoresizingMask,这是关键self.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;infoLabel.autoresizingMask = dateLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin ;@end
0 0