我想在导航栏中使用两个UILabels而不是一个。ios标题和字幕在导航栏中居中
我跟着这个链接,就如何做到这一点的信息: iPhone Title and Subtitle in Navigation Bar
它运作良好,但我不能让我的文字要正确居中。 它位于按钮之间,但是默认的标题行为是在时间的下方居中。
我在这里一看,同样的问题,但没有答案: 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;
非常感谢!它现在有效。但我不明白。为什么当给定尺寸更高时它不居中? – user2700551
它不适用于所有不同的情况。虽然它适用于此后退按钮,但左侧的后退按钮可以更宽,标题向右移动。 – user2700551
文字始终以标签为中心。所以你应该相应地调整标签的宽度。如果为测试标签设置了backgroundcolor,那么你会得到清晰的想法。如果你能够接受并且赞同答案,那么它会非常可观。 –