iOS 导航栏自定义 TitleView不居中的问题

#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







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值