如何为一个视图控制器设置UINavigation栏的titletextattributes?

时间:2012-10-09 21:57:33

标签: ios xcode uinavigationcontroller uinavigationbar viewdidload

我正在尝试更改我的一个视图控制器的字体大小,因为它适用于更多文本,因此需要比我的其他视图更小的字体大小。我在didFinishLaunchingWithOptions期间在appdelegate中设置导航栏属性,然后在viewDidLoad期间为我的视图控制器设置字体。但是,当我返回屏幕或向前时,我保留对导航栏所做的更改,即较小的字体。有没有解决的办法?例如,在退出视图时将字体设置回正常状态?

Cliffsnotes:尝试在一个视图控制器中设置字体,但是一旦我设置它,它就适用于所有视图控制器。

代码如下:

在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]];

2 个答案:

答案 0 :(得分:3)

导航控制器中的所有视图控制器共享导航栏。因此,一旦更改了导航栏,同一导航堆栈中的所有视图控制器都将受到影响。一种选择是为这个视图控制器设置自定义titleView。

self.navigationItem.titleView = ... // some UILabel with the desired formatting

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

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

答案 1 :(得分: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];