如何为一个视图控制器设置导航栏的标题文本属性?

4
我正在尝试更改一个视图控制器的字体大小,因为它需要更多的文本,因此需要比我的其他视图更小的字体大小。我在didFinishLaunchingWithOptions中设置了应用程序委托中的导航栏属性,然后在viewDidLoad中设置了我要处理的视图控制器的字体。但是,当我返回一个屏幕或前进一个屏幕时,我对导航栏所做的更改被保留,即较小的字体。有没有办法解决这个问题?例如,在退出视图时将字体设置回正常值等。

简而言之:尝试在一个视图控制器中设置字体,但一旦设置,它将应用于所有视图控制器。

代码如下:

在AppDelegate中:

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navbar.png"] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor clearColor],
  UITextAttributeTextColor,
  [UIColor whiteColor],
  UITextAttributeTextShadowColor,
  [NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
  UITextAttributeTextShadowOffset,
  [UIFont fontWithName:@"QuicksandBold-Regular" size:24.0],
  UITextAttributeFont,
  nil]];

在视图控制器的viewDidLoad方法中:

[self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor clearColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor whiteColor],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, -1)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"QuicksandBold-Regular" size:18.0],
                                                                     UITextAttributeFont,
                                                                     nil]];

我尝试使用您的解决方案编辑标题颜色: NSDictionary *titleTextAttributes = [[UINavigationBar appearance] titleTextAttributes]; [titleTextAttributes setValue:[UIColor colorWithRed:0.48627454040000001 green:0.050980396570000003 blue:0.13725490870000001 alpha:1] forKey:UITextAttributeTextColor]; [[UINavigationBar appearance] setTitleTextAttributes:titleTextAttributes]; 但是不起作用:S! - IgniteCoders
2个回答

3
导航栏是导航控制器中所有视图控制器共享的。因此,一旦更改了导航栏,同一导航堆栈中的所有视图控制器都将受到影响。其中一种选择是为此视图控制器设置自定义titleView。
self.navigationItem.titleView = ... // some UILabel with the desired formatting

这样,只有一个视图控制器显示自定义标题。

另一种选择是在视图控制器的viewWillAppear方法中更改导航栏的外观,然后在视图控制器的viewWillDisappear方法中重置它。但这种方法可能不如使用自定义titleView顺畅。


Coolio,我完全忘记了viewWillDisappear方法,正是我要找的。 - Hudson Buddy

0

所以,现在你的属性键已经过时了。请使用以下键:

NSDictionary* attributes = [NSDictionary dictionaryWithObjectsAndKeys:
 [UIColor clearColor], NSForegroundColorAttributeName,
 [UIColor whiteColor], NSShadowAttributeName,
 [NSValue valueWithUIOffset:UIOffsetMake(0, -1)], NSShadowAttributeName,
 [UIFont fontWithName:@"QuicksandBold-Regular" size:24.0], NSFontAttributeName,
 nil];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接