UINavigationController 的 title 居中显示 (UINavigationController 的 title 文字多时居中显示)

一次偶然的机,我发现了,原来当 title 文字想对多时,是会靠左显示而不是居中显示,尴尬,处理起来也不是特别方便,可能你时间费了也解决不掉。这时候有些小朋友就说了,这太简单了,我搞一个 label 赋给 titleview ,完了设置 label 文字居中就好了,如果有这样想的朋友我希望你去试试,是不对滴,我这提供一种做法,供参考,如果能帮你解决问题,麻烦点赞鼓励,谢谢

- (void)setDisplayCustomTitleText:(NSString*)text

{

    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(35, 0, SCREEN_WIDTH, 44)];

    titleView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

    titleView.autoresizesSubviews = YES;

    titleView.backgroundColor = [UIColor clearColor];

    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(35, 0, SCREEN_WIDTH, 44)];

    titleLabel.backgroundColor = [UIColor clearColor];

    titleLabel.textAlignment = NSTextAlignmentCenter;

    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

    titleLabel.textColor = [UIColor orangeColor];

    titleLabel.lineBreakMode = NSLineBreakByTruncatingTail;

    titleLabel.autoresizingMask = titleView.autoresizingMask;

    CGRect leftViewbounds = self.navigationItem.leftBarButtonItem.customView.bounds;

    CGRect rightViewbounds = self.navigationItem.rightBarButtonItem.customView.bounds;

    

    CGRect frame;

    CGFloat maxWidth = leftViewbounds.size.width > rightViewbounds.size.width ? leftViewbounds.size.width : rightViewbounds.size.width;

    

    frame = titleLabel.frame;

    frame.size.width = SCREEN_WIDTH - maxWidth * 2;

    titleLabel.frame = frame;

    

    frame = titleView.frame;

    frame.size.width = SCREEN_WIDTH - maxWidth * 2;

    titleView.frame = frame;

    

    titleLabel.text = text;

    [titleView addSubview:titleLabel];

    self.navigationItem.titleView = titleView;

}


错误的效果图


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值