UINavigationBar自iOS6以来未alignment的标题

自从iOS 6以来,我在我的应用程序中使用自定义样式有几个问题。 我使用自定义字体和几个UIAppearance代理。 我无法理解的问题是UINavigationBar中标题的错位。 在iOS 5中一切正常,并正确alignment。

由于iOS6已经发布,自定义样式并不less见,我认为这不是一个错误,但我误解了对iOS6的一些新变化。

错位

我已经search了一个文本alignment方法来调用UIAppearance代理的文档,但我无法find这样的方法。

我使用下面的代码行来在我的整个应用程序中设置我的UINavigationBar:

 [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarMetrics:UIBarMetricsDefault]; [[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"NavigationBarBackground"] forBarMetrics:UIBarMetricsLandscapePhone]; [[UINavigationBar appearance] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor whiteColor], UITextAttributeTextColor, [UIFont fontWithName:@"Corbel-Bold" size:14.0], UITextAttributeFont, nil]]; [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:[UIColor whiteColor]]; [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys: [UIColor ceBlueColor], UITextAttributeTextColor, [UIColor whiteColor], UITextAttributeTextShadowColor, [NSValue valueWithUIOffset:UIOffsetMake(0, 1)], UITextAttributeTextShadowOffset, [UIFont fontWithName:@"Corbel" size:0.0], UITextAttributeFont, nil] forState:UIControlStateNormal]; [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -3) forBarMetrics:UIBarMetricsDefault]; 

同样的问题在这里,但我注意到,当导航栏有一个后退button或一个正确的酒吧button(表编辑)不会发生。 导航到一个新的视图控制器,然后返回到第一个时,标题上的alignment也是固定的…

我觉得这是iOS计算基于默认字体标题的框架的位置,因为我使用的字体有点小,标题偏离了中心的左侧。

我目前的修复方法是在viewWillAppear中调用setNeedsLayout 。 似乎正在工作。

 - (void) viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (self.navigationItem.hidesBackButton || self.navigationItem.rightBarButtonItem == nil) { [self.navigationController.navigationBar setNeedsLayout]; } } 

如果有帮助,您可以调整(至less)标题的垂直位置:

 [[UINavigationBar appearance] setTitleVerticalPositionAdjustment:4 forBarMetrics:UIBarMetricsDefault]; 

(这个问题帮我find了解决这个问题的方法: UINavigationBar自定义标题位置 )