4

从 iOS 6 开始,我在应用程序中使用自定义样式时遇到了几个问题。我使用自定义字体和几个UIAppearance代理。我无法理解的一个问题是我的 UINavigationBar 中的标题未对齐。在 iOS 5 中,一切正常并正确对齐。

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

错位

我在文档中搜索了用于调用 UIAppearance 代理的文本对齐方法,但我找不到这样的方法。

我使用以下代码行在整个应用程序中设置 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];
4

2 回答 2

12

这里有同样的问题,但我注意到当导航栏有后退按钮或右栏按钮(表格编辑)时不会发生这种情况。导航到新视图控制器然后返回第一个视图控制器时,标题上的对齐方式也已修复...

我认为正在发生的事情是iOS根据默认字体计算标题框架的位置,因为我使用的字体有点小,标题有点偏向中心左侧。

我当前的修复是调用setNeedsLayoutviewWillAppear。似乎正在工作。

- (void) viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    if (self.navigationItem.hidesBackButton || self.navigationItem.rightBarButtonItem == nil) {
        [self.navigationController.navigationBar setNeedsLayout];
    }
}
于 2012-11-04T12:14:06.460 回答
5

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

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

(这个问题帮助我找到了解决这个问题的方法:UINavigationBar custom title position

于 2013-04-09T12:13:57.760 回答