如何更改自定义NavigationItem标题和背景颜色?

时间:2014-05-02 14:21:18

标签: ios uinavigationbar

之前我使用了一个带有此代码的导航控制器:

self.navigationItem.title = @"News";

现在我遇到的问题是我不再需要导航控制器,因为我正在使用页面控制器进行导航。现在我添加了一个导航栏,但它不再使用此代码更改标题。

另外如何更改背景颜色?

2 个答案:

答案 0 :(得分:3)

在iOS 7中,使用didFinishLaunchingWithOptions

中的以下代码
if ([[UINavigationBar class] respondsToSelector:@selector(appearance)]) 
{
     [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed: 4.0/255.0 green:173.0/255.0 blue:214.0/255.0 alpha:1.0f ]]; //// change background color of navigationBar
     [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]]; /// set backButton color of navigation bar
     [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor whiteColor]}]; // set title color 
     [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor,nil] forState:UIControlStateNormal];  /// set all barButton item color
     self.navController.navigationBar.translucent = NO;// set translucent NO
}

根据您的要求使用。

答案 1 :(得分:0)

所以当你使用一个你没有看到的导航控制器时会发生一些神奇的事情,现在你已经开始使用导航栏进行调整而失去了魔力。

导航栏负责管理和呈现UNavigationItems,并因此保存它们的数组。 NavigationItem包含左右按钮,标题或titleView等内容。当您的导航控制器推送新控制器时,它会创建一个全新的UINavigation项目,然后将其链接到您的新视图控制器,然后将其推送到导航栏堆栈的导航项目。这就是为什么在视图控制器中使用self.navigationItem.title设置标题而不是引用导航栏。

基本上你必须自己管理吧台和导航项目。这应该是为你做的:

_navBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, yOffset, CGRectGetHeight(size), height)];
_navItem = [[UINavigationItem alloc] initWithTitle:@"My navbar title"];
[_navBar setItems:@[_navItem]];

[self.view addSubview:_navBar];

当然,您必须以不同的方式管理大小,因为我的示例来自于在横向模式下使用的应用。