一次偶然的机,我发现了,原来当 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;
}