2013-08-20 127 views
5

我想在导航栏中使用两个UILabels而不是一个。ios标题和字幕在导航栏中居中

我跟着这个链接,就如何做到这一点的信息: iPhone Title and Subtitle in Navigation Bar

它运作良好,但我不能让我的文字要正确居中。 它位于按钮之间,但是默认的标题行为是在时间的下方居中。

enter image description here

我在这里一看,同样的问题,但没有答案: UINavigationBar TitleView with subtitle

我缺少什么? 这里是我的代码:

CGRect headerTitleSubtitleFrame = CGRectMake(0, 0, 200, 44); 
UIView* _headerTitleSubtitleView = [[UILabel alloc] initWithFrame:headerTitleSubtitleFrame]; 
_headerTitleSubtitleView.backgroundColor = [UIColor clearColor]; 
_headerTitleSubtitleView.autoresizesSubviews = NO; 

CGRect titleFrame = CGRectMake(0, 2, 200, 24); 
UILabel *titleView = [[UILabel alloc] initWithFrame:titleFrame]; 
titleView.backgroundColor = [UIColor clearColor]; 
titleView.font = [UIFont boldSystemFontOfSize:20]; 
titleView.textAlignment = NSTextAlignmentCenter; 
titleView.textColor = [UIColor whiteColor]; 
titleView.shadowColor = [UIColor darkGrayColor]; 
titleView.shadowOffset = CGSizeMake(0, -1); 
titleView.text = @"Title"; 
titleView.adjustsFontSizeToFitWidth = YES; 
[_headerTitleSubtitleView addSubview:titleView]; 

CGRect subtitleFrame = CGRectMake(0, 24, 200, 44-24); 
UILabel *subtitleView = [[UILabel alloc] initWithFrame:subtitleFrame]; 
subtitleView.backgroundColor = [UIColor clearColor]; 
subtitleView.font = [UIFont boldSystemFontOfSize:13]; 
subtitleView.textAlignment = NSTextAlignmentCenter; 
subtitleView.textColor = [UIColor whiteColor]; 
subtitleView.shadowColor = [UIColor darkGrayColor]; 
subtitleView.shadowOffset = CGSizeMake(0, -1); 
subtitleView.text = @"Subtitle"; 
subtitleView.adjustsFontSizeToFitWidth = YES; 
[_headerTitleSubtitleView addSubview:subtitleView]; 

self.navigationItem.titleView = _headerTitleSubtitleView; 

回答

10

你应该同时调整帧的宽度。它应该低于200.试试这个。

CGRect titleFrame = CGRectMake(0, 2, 160, 24); 
CGRect subtitleFrame = CGRectMake(0, 24, 160, 44-24); 

编辑:您左侧的后退更宽,titleview右移。

请看宽度为200像素 enter image description here

我建议你调整titleview的宽度,并标示出相应的图像和宽度160像素 enter image description here

图像。

如果您想了解更多关于后扣宽度的信息,请参阅此处的讨论。 SO Post 1.

SO Post 2.

+0

非常感谢!它现在有效。但我不明白。为什么当给定尺寸更高时它不居中? – user2700551

+0

它不适用于所有不同的情况。虽然它适用于此后退按钮,但左侧的后退按钮可以更宽,标题向右移动。 – user2700551

+0

文字始终以标签为中心。所以你应该相应地调整标签的宽度。如果为测试标签设置了backgroundcolor,那么你会得到清晰的想法。如果你能够接受并且赞同答案,那么它会非常可观。 –

1

你可能喜欢UINavigationItem类此属性。

@property (nonatmic,copy) NSString *prompt

它很优雅。

+3

但这增加了整个导航栏的高度。它在标题之上,而不是在它之下。 –