iPhone导航栏标题文字颜色

289

默认情况下,iOS导航栏标题颜色为白色。是否有方法将其更改为其他颜色?

我知道可以使用navigationItem.titleView方法使用图像的方式进行更改。由于我的设计技能有限并且我未能获得标准的光泽效果,因此我更喜欢更改文本颜色。

非常感谢您的任何见解。


我刚发布了一段代码,基于Steven Fisher的答案,简化了添加自定义彩色标题到导航栏的过程。它还支持更改标题。去找找吧!它不会让你失望的。 - Erik B
1
Erik: 我已经在我的答案中加了一条关于你的回答的注释。我可以用你的代码更新我的答案,但我不想获得你的点赞。顺便说一句,聪明的解决方案。 - Steven Fisher
针对IOS 13 https://dev59.com/3bbna4cB1Zd3GeqPcYqd#61141195 - Vladyslav Panchenko
32个回答

424

现代方法

现代的方式,对于整个导航控制器...在您的导航控制器根视图加载时执行此操作。

[self.navigationController.navigationBar setTitleTextAttributes:
   @{NSForegroundColorAttributeName:[UIColor yellowColor]}];

然而,这似乎对后续视图没有影响。

传统方法

旧的方式是针对每个视图控制器(这些常量是用于iOS 6的,但如果要在iOS 7上以每个视图控制器为基础进行设置,则需要采取相同的方法但使用不同的常量):

您需要使用一个UILabel作为navigationItemtitleView

标签应该:

  • 具有清晰的背景颜色(label.backgroundColor = [UIColor clearColor])。
  • 使用粗体20pt系统字体(label.font = [UIFont boldSystemFontOfSize: 20.0f])。
  • 具有50%透明度的黑色阴影(label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5])。
  • 您还需要将文本对齐设置为居中(label.textAlignment = NSTextAlignmentCenter(对于旧的SDK,请使用UITextAlignmentCenter)。

将标签文字颜色设置为任何自定义颜色。您需要选择一种颜色,使文本不会与阴影混合在一起,这会使其难以阅读。

我通过尝试和错误来解决这个问题,但我得出的值最终过于简单,以至于它们不是苹果选定的值。 :)

如果您想要验证此内容,请将此代码放入Apple的导航栏示例中的PageThreeViewController.m中的initWithNibName:bundle:中。这将用黄色标签替换文本。除了颜色之外,这应该与Apple代码生成的原始标签无法区分。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        // this will appear as the title in the navigation bar
        UILabel *label = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
        label.backgroundColor = [UIColor clearColor];
        label.font = [UIFont boldSystemFontOfSize:20.0];
        label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
        label.textAlignment = NSTextAlignmentCenter;
                           // ^-Use UITextAlignmentCenter for older SDKs.
        label.textColor = [UIColor yellowColor]; // change this color
        self.navigationItem.titleView = label;
        label.text = NSLocalizedString(@"PageThreeTitle", @"");
        [label sizeToFit];
    }

    return self;
}

编辑:此外,请阅读下面Erik B的答案。我的代码展示了效果,但他的代码提供了一种更简单的方法将其放置在现有视图控制器中。


2
如果您使用sizeWithFont:将标签框架设置为其文本大小,则它将神奇地采用标准标签的自动对齐行为。 - grahamparks
1
但是如果您使用sizeToFit,您将失去自动截断功能。 - Steven Fisher
3
好的,我会尽力为您翻译。以下是需要翻译的内容:注意:这是设置自定义标题的旧方法,我建议阅读Erik B.的答案。 - Elia Palme
1
确认 sizeToFit 起作用了,因此更新了答案。另外,添加了阅读 Erik B 的答案的注释。 - Steven Fisher
1
label.textAlignment = UITextAlignmentCenter 自 iOS6.0 起已被弃用,请使用 NSTextAlignmentCenter 代替。 - Jasper
显示剩余16条评论

226

我知道这是一个很老的帖子,但我认为对于新用户来说,了解iOS 5引入了一种用于建立标题属性的新属性会很有用。

您可以使用setTitleTextAttributes设置字体、颜色、偏移和阴影颜色来设置UINavigationBar的标题属性。

此外,您还可以为整个应用程序中的所有UINavigationBars设置相同的默认UINavigationBar标题文本属性。

例如:

NSDictionary *navbarTitleTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:
                                            [UIColor whiteColor],UITextAttributeTextColor, 
                                            [UIColor blackColor], UITextAttributeTextShadowColor, 
                                            [NSValue valueWithUIOffset:UIOffsetMake(-1, 0)], UITextAttributeTextShadowOffset, nil];

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];

11
在iOS 7中,“UITextAttributeTextColor”已经被弃用。iOS 7使用“NSForegroundColorAttributeName”代替该键。 - Keller
1
请注意,这将更改所有导航栏,通常这正是您想要的。 - Ash
1
请将此标记为正确答案 - 使用这些可用的方法,上面的UILabel方法是不必要的。 - Mic Fok

180
在iOS 5中,你可以通过以下方式更改navigationBar标题的颜色:
navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

8
我同意!对于iOS 7,将UITextAttributeTextColor更新为NSForegroundColorAttributeName。非常好用! - John Erck
这个可行!我想要了解的是如何做到的?titleTextAttributes 接受一个字典,其中包含在“NSString UIKit Additions Reference”下提到的“文本属性字典键”中预定义的一组键。它是如何接受你提到的键的呢? - AceN
...而且它正在工作,我如何获取“默认”的色调? - AceN
设置 self.navigationController.navigationBar.tintColor 对我没有起作用。这个可以。 - JRam13

128

参考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];
}

这段代码的优点,除了可以正确处理框架外,还包括:如果您更改控制器的标题,则自定义标题视图也将被更���。无需手动更新。

另一个重要的优势是它使自定义标题颜色变得非常简单。您只需要将此方法添加到控制器即可。


3
我同意这个确实是最好的解决方案。不需要使用sizeWithFont,我喜欢覆盖setTitle方法的想法。 - Elia Palme
@Sr.Richie,您不应该将代码放在自定义导航控制器中。您应该将其放在需要更改标题颜色的所有视图控制器中。您可能甚至不需要自定义导航控制器。 - Erik B
对我来说不起作用。我认为这是因为我使用了[UINavigationBar appearance]方法..(不起作用是因为标签titleView始终为空) - Matej
1
如果您使用的是iOS5或更高版本,则应阅读下面minus的答案。有一个一行代码可以正常工作并保持在预订状态。 - algal
我们需要在viewDidLoad中添加self.title=@"我们的字符串";,然后上面的代码才能正常工作。 - Hari1251

40

以上大部分建议现在已被废弃,在iOS 7中使用 -

NSDictionary *textAttributes = [NSDictionary dictionaryWithObjectsAndKeys: 
                               [UIColor whiteColor],NSForegroundColorAttributeName, 
                               [UIColor whiteColor],NSBackgroundColorAttributeName,nil];

self.navigationController.navigationBar.titleTextAttributes = textAttributes;
self.title = @"Title of the Page";

还有,请查看NSAttributedString.h以获取可以设置的各种文本属性。


38

在 iOS 7 和 8 中,您可以将标题的颜色更改为绿色。

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

6
self.navigationController!.navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as [NSObject : AnyObject]self.navigationController!.navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as [NSObject : AnyObject] - Byron Coetsee
@ByronCoetsee 在更新到Swift 2之后,我遇到了以下错误:无法将类型为'[NSObject : AnyObject]'的值分配给类型为'[String : AnyObject]?'的值。 - Jorge Casariego
2
在Swift 2.0中,这个操作变得更加容易了:self.navigationController!.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.whiteColor()] - Kevin DiTraglia

24
为了让问题保持更新,我会添加 Alex R. R. 的解决方案,但是使用 Swift 实现:
self.navigationController.navigationBar.barTintColor = .blueColor()
self.navigationController.navigationBar.tintColor = .whiteColor()
self.navigationController.navigationBar.titleTextAttributes = [
    NSForegroundColorAttributeName : UIColor.whiteColor()
]

这导致的结果是:

在这里输入图片描述


嗯,也许它不适用于Swift 2.0。让我再确认一下。不过没必要那么激动。 - Michal
抱歉Michal,我当时是开玩笑的!并不是有攻击性的!对我有效的代码更像是这样的:self.navigationController!.navigationBar.titleTextAttributes = NSDictionary(object: UIColor.whiteColor(), forKey: NSForegroundColorAttributeName) as [NSObject : AnyObject] - Radu
在这行代码之前添加以下代码: UINavigationBar.appearance().barStyle = UIBarStyle.Black 以使tintColor生效! - triiiiista
2
在Swift 4.0中: self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor : UIColor.white] - Abhi Muktheeswarar

14

Swift版本

我发现大部分人提供的答案都是Objective-C版本的。

我想为那些需要的人使用Swift实现这个函数。

在ViewDidload中:

1.将NavigationBar的背景颜色更改为蓝色(例如:BLUE)。

self.navigationController?.navigationBar.barTintColor = UIColor.blueColor()

2.将NavigationBar的背景变为图片(例如:ABC.png)

let barMetrix = UIBarMetrics(rawValue: 0)!

self.navigationController?.navigationBar
      .setBackgroundImage(UIImage(named: "ABC"), forBarMetrics: barMetrix)

3. 更改NavigationBar标题(例如:[字体:Futura,10] [颜色:红色])

navigationController?.navigationBar.titleTextAttributes = [
            NSForegroundColorAttributeName : UIColor.redColor(),
            NSFontAttributeName : UIFont(name: "Futura", size: 10)!
        ]

(提示1:别忘了在UIFont后面加上"!"号)

(提示2:标题文本有很多属性,请单击“NSFontAttributeName”以进入类并查看keyNames和它们所需的对象类型)

我希望我能帮忙!:D


14

方法1,在IB中设置:

输入图像描述

方法2,一行代码:

navigationController?.navigationBar.barTintColor = UIColor.blackColor()

方法二不起作用。只能使用 titleTextAttributes - Vyachaslav Gerchicov

13

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

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