导航栏中的ios标题和副标题居中

我正在尝试在导航栏中安装两个UILabel而不是一个。

我按照此链接获取有关如何执行此操作的信息: 导航栏中的iPhone标题和副标题

它运作良好,但我不能让我的文本正确居中。 它在按钮之间居中,但默认的标题行为是在正确的时间内居中。

在此处输入图像描述

我看过这里,同样的问题,但没有答案: UINavigationBar TitleView带副标题

我错过了什么? 这是我的代码:

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; 

您应该调整两个帧的宽度。 它应该低于200.试试这个。

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

编辑:左侧的后退按钮较宽,标题视图向右移动。

请查看宽度为200px的图像 在此处输入图像描述

并且图像宽度为160px 在此处输入图像描述

我建议你相应调整titleview的宽度和标签。

如果您想了解更多关于后退按钮的宽度,请参考此处的讨论。 所以发布1。

SO Post 2。

您可能喜欢UINavigationItem类中的此属性。

@property (nonatmic,copy) NSString *prompt

它很优雅。