在不同的视图控制器中更改导航栏标题(字体和颜色)

时间:2011-11-17 11:48:31

标签: iphone uitableview navigationcontroller navigationbar

我试图在我的应用中自定义导航栏标题的外观。

我必须构建自定义导航控制器(不只是针对此问题),所以我想覆盖setTitle函数,就像这样

- (void)setTitle:(NSString *)title
{
    NSLog(@"SETTING TITLE %@", title);
   [super setTitle:title];
   UILabel *titleView = (UILabel *)self.navigationBar.topItem.titleView;
   NSLog(@"title view is %@", titleView);
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont fontWithName:@"TradeGothicLTStd-Bold-Accent-Accent" size:20];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        titleView.textColor = [UIColor whiteColor];
        self.navigationBar.topItem.titleView = titleView;
        [titleView release];
    }
    titleView.text = [title uppercaseString];
    [titleView sizeToFit];

    self.navigationBar.tintColor= [UIColor colorWithRed:130.0f/255.0f green:120.0f/255.0f blue:90.0f/255.0f alpha:1.0f];
}

一切都按预期工作。 现在问题是在导航控制器内部我有一个TableView。当单击一个单元格时,该应用程序向下钻取到另一个TableView,它应该再次具有自定义标题。

这是didSelectRowAtIndexPath:

的代码
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSString *category_id = [[managedObject valueForKey:@"category_id"] stringValue];
    NSString *name = [[[managedObject valueForKey:@"name"] description] capitalizedString];
    CategoryViewController *category = [[CategoryViewController alloc] initWithNibName:@"CategoryViewController" bundle:nil];
    category.category_id = category_id;
    category.name = name;
    category.managedObjectContext = self.managedObjectContext;
    // ...
    // Pass the selected object to the new view controller.
    [self.navigationController pushViewController:category animated:YES];
    [category release];
}

....但是当显示所选视图时,它会显示标准字体。

修改 我注意到如果在第二个视图中我在viewDidAppear方法中设置了标题,它会发生不同的事情。 如果我写

- (void)viewDidAppear:(BOOL)animated
{
self.navigationController.title = name;
[super viewDidAppear:animated];
}

...导航栏中的标题有正确的(自定义)字体,但标题就像只有在视图完成滑入时才出现....? 再说一遍,我显然在这里做错了,任何帮助都会受到赞赏:)

你的时间!

4 个答案:

答案 0 :(得分:8)

代码段

[[UINavigationBar appearance] setTintColor:[UIColor colorWithRed:107.0/256.0 green:145.0/256.0 blue:35.0/256.0 alpha:1.0]]; 

将更改整个应用程序导航栏的颜色。

将它放在Appdelegate的didFinishLauncing方法中。

答案 1 :(得分:7)

从iOS 5开始,您可以直接使用UINavigationBar

执行此操作

https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UINavigationBar_Class/Reference/UINavigationBar.html 自定义导航栏的外观

只需设置titleTextAttributes字典

即可

答案 2 :(得分:0)

对于iOS7及更高版本,解决方案是:

[UINavigationBar appearance].barTintColor = [UIColor redColor];

将此代码粘贴到AppDelegate(didFinishLaunching :)方法中,一切都应该可以正常工作。

答案 3 :(得分:-1)

请使用viewDidAppear方法,而不是在viewDidLoad方法中进行设置。