iOS导航栏的标题颜色默认是白色。有没有办法换一种颜色?

我知道navigationItem。使用图像的titleView方法。由于我的设计技能有限,我没有得到标准的光泽,我更喜欢改变文字的颜色。

任何见解都将非常感激。


当前回答

在iOS 5中,你可以这样改变navigationBar标题的颜色:

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

其他回答

在iOS 5中,你可以这样改变navigationBar标题的颜色:

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

如果你试图改变一个页面的颜色,tewha的解决方案效果很好,但我希望能够改变每个页面的颜色。我做了一些小的修改,使它可以工作在UINavigationController上的所有页面

NavigationDelegate.h

//This will change the color of the navigation bar
#import <Foundation/Foundation.h>
@interface NavigationDelegate : NSObject<UINavigationControllerDelegate> {
}
@end

NavigationDelegate.m

#import "NavigationDelegate.h"
@implementation NavigationDelegate

- (void)navigationController:(UINavigationController *)navigationController 
      willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    CGRect frame = CGRectMake(0, 0, 200, 44);//TODO: Can we get the size of the text?
    UILabel* label = [[[UILabel alloc] initWithFrame:frame] autorelease];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont boldSystemFontOfSize:20.0];
    label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
    label.textAlignment = UITextAlignmentCenter;
    label.textColor = [UIColor yellowColor];
    //The two lines below are the only ones that have changed
    label.text=viewController.title;
    viewController.navigationItem.titleView = label;
}
@end

在IOS 7和8中,你可以将标题的颜色改为绿色

self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];

这适用于我在Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]

根据Steven Fisher的回答,我写了这样一段代码:

- (void)setTitle:(NSString *)title
{
    [super setTitle:title];
    UILabel *titleView = (UILabel *)self.navigationItem.titleView;
    if (!titleView) {
        titleView = [[UILabel alloc] initWithFrame:CGRectZero];
        titleView.backgroundColor = [UIColor clearColor];
        titleView.font = [UIFont boldSystemFontOfSize:20.0];
        titleView.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];

        titleView.textColor = [UIColor yellowColor]; // Change to desired color

        self.navigationItem.titleView = titleView;
        [titleView release];
    }
    titleView.text = title;
    [titleView sizeToFit];
}

这段代码的优点,除了正确地处理帧,是如果你改变你的控制器的标题,自定义标题视图也会得到更新。无需手动更新。

另一个很大的优势是,它使得启用自定义标题颜色非常简单。您所需要做的就是将这个方法添加到控制器中。