ios iPhone 导航栏标题文字颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/599405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:42:21  来源:igfitidea点击:

iPhone Navigation Bar Title text color

iosuinavigationbarnavigationitem

提问by Steven Fisher

It seems the iOS Navigation Bar title color is white by default. Is there a way to change it to a different color?

默认情况下,iOS 导航栏标题颜色似乎是白色的。有没有办法将其更改为不同的颜色?

I am aware of the navigationItem.titleViewapproach using an image. Since my design skills are limited and I failed to get the standard glossy, I prefer changing the text color.

我知道navigationItem.titleView使用图像的方法。由于我的设计技巧有限并且​​我未能获得标准光泽,我更喜欢更改文本颜色。

Any insight would be much appreciated.

任何见解将不胜感激。

回答by Steven Fisher

Modern approach

现代方法

The modern way, for the entire navigation controller…?do this once, when your navigation controller's root view is loaded.

现代的方式,对于整个导航控制器...?做一次,当你的导航控制器的根视图加载时。

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

However, this doesn't seem have an effect in subsequent views.

但是,这在后续视图中似乎没有影响。

Classic approach

经典方法

The old way, per view controller (these constants are for iOS 6, but if want to do it per view controller on iOS 7 appearance you'll want the same approach but with different constants):

旧方式,每个视图控制器(这些常量适用于 iOS 6,但如果想在 iOS 7 外观上为每个视图控制器执行此操作,您将需要相同的方法,但具有不同的常量):

You need to use a UILabelas the titleViewof the navigationItem.

您需要使用 aUILabel作为titleViewnavigationItem

The label should:

标签应该:

  • Have a clear background color (label.backgroundColor = [UIColor clearColor]).
  • Use bold 20pt system font (label.font = [UIFont boldSystemFontOfSize: 20.0f]).
  • Have a shadow of black with 50% alpha (label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5]).
  • You'll want to set the text alignment to centered as well (label.textAlignment = NSTextAlignmentCenter(UITextAlignmentCenterfor older SDKs).
  • 具有清晰的背景颜色 ( label.backgroundColor = [UIColor clearColor])。
  • 使用粗体 20pt 系统字体 ( label.font = [UIFont boldSystemFontOfSize: 20.0f])。
  • 具有 50% alpha ( label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5])的黑色阴影。
  • 您还需要将文本对齐设置为居中(label.textAlignment = NSTextAlignmentCenterUITextAlignmentCenter对于较旧的 SDK)。

Set the label text color to be whatever custom color you'd like. You do want a color that doesn't cause the text to blend into shadow, which would be difficult to read.

将标签文本颜色设置为您喜欢的任何自定义颜色。您确实需要一种不会导致文本混合到难以阅读的阴影中的颜色。

I worked this out through trial and error, but the values I came up with are ultimately too simple for them not to be what Apple picked. :)

我通过反复试验解决了这个问题,但我想出的价值观最终太简单了,它们不是 Apple 选择的。:)

If you want to verify this, drop this code into initWithNibName:bundle:in PageThreeViewController.mof Apple's NavBar sample. This will replace the text with a yellow label. This should be indistinguishable from the original produced by Apple's code, except for the color.

如果你想验证这一点,放弃这一代码到initWithNibName:bundle:PageThreeViewController.m苹果的NavBar样品。这将用黄色标签替换文本。除了颜色之外,这应该与 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;
}

Edit: Also, read Erik B's answer below. My code shows the effect, but his code offers a simpler way to drop this into place on an existing view controller.

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

回答by Alex R. R.

I know this is a pretty old thread, but I think it would be useful to know for new users that iOS 5 brings a new property for establishing title properties.

我知道这是一个很老的话题,但我认为让新用户知道 iOS 5 为建立标题属性带来了一个新属性会很有用。

You can use UINavigationBar's setTitleTextAttributesfor setting the font, color, offset, and shadow color.

您可以使用 UINavigationBarsetTitleTextAttributes来设置字体、颜色、偏移量和阴影颜色。

In addition you can set the same default UINavigationBar's Title Text Attributes for all the UINavigationBarsthroughout your application.

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

For example like so:

例如像这样:

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

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];

回答by minux

In iOS 5 you can change the navigationBar title color in this manner:

在 iOS 5 中,您可以通过以下方式更改导航栏标题颜色:

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

回答by Erik B

Based on Steven Fisher's answer I wrote this piece of code:

根据史蒂文·费舍尔的回答,我写了这段代码:

- (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];
}

The advantage of this code, besides dealing with the frame properly, is that if you change the title of your controller the custom title view will also get updated. No need to update it manually.

这段代码的优点是,除了正确处理框架之外,如果您更改控制器的标题,自定义标题视图也会更新。无需手动更新。

Another big advantage is that it makes it really simple to enable custom title color. All you need to do is to add this method to the controller.

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

回答by girish_vr

Most of the above suggestions are deprecated now, for iOS 7 use -

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

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

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

Also, checkout the NSAttributedString.h for various text properties that could be set.

此外,检查 NSAttributedString.h 以获取可以设置的各种文本属性。

回答by Pramesh

In IOS 7 and 8, you can change the Title's color to let's say green

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

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

回答by Michal

To keep the question up-to-date, I'll add Alex R. R.solution, but in Swift:

为了使问题保持​​最新,我将添加Alex RR解决方案,但在Swift 中

self.navigationController.navigationBar.barTintColor = .blueColor()
self.navigationController.navigationBar.tintColor = .whiteColor()
self.navigationController.navigationBar.titleTextAttributes = [
    NSForegroundColorAttributeName : UIColor.whiteColor()
]

Which results to:

结果是:

enter image description here

在此处输入图片说明

回答by fujianjin6471

Method 1, set it in IB:

方法一,在IB中设置:

enter image description here

在此处输入图片说明

Method 2, one line of code:

方法二,一行代码:

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

回答by Microos

SwiftVersion

迅捷

I found most of you guys presented the answers of Objective_C version

我发现你们大多数人都给出了Objective_C版本的答案

I would like to implement this function by using Swift for anyone who needs it.

我想为任何需要它的人使用 Swift 来实现这个功能。

In ViewDidload

在 ViewDidload 中

1.To make NavigationBar background becomes color (for example: BLUE)

1.使NavigationBar背景变成彩色(例如:BLUE)

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

2.To make NavigationBar background becomes Image (for example : ABC.png)

2.让NavigationBar背景变成Image(例如:ABC.png)

let barMetrix = UIBarMetrics(rawValue: 0)!

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

3.To change NavigationBar title (for example :[Font:Futura,10] [Color:Red])

3.更改导航栏标题(例如:[Font:Futura,10] [Color:Red])

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

(hint1: don't forget the "!" mark after the UIFont)

(hint2: there are lots of attributes of the title text, command click the "NSFontAttributeName" you can enter the class and view keyNames and the Objects types they required)

(提示 1:不要忘记 UIFont 后面的“!”标记)

(提示2:标题文本的属性很多,命令点击“NSFontAttributeName”可以进入类,查看keyNames和他们需要的Objects类型)

I hope I can help!:D

希望能帮到你!:D

回答by Sandeep

From iOS 5 onwards we have to set title text color and font of navigation bar using titleTextAttribute Dictionary(predefined dictionary in UInavigation controller class reference).

从 iOS 5 开始,我们必须使用 titleTextAttribute 字典(UInavigation 控制器类参考中的预定义字典)设置导航栏的标题文本颜色和字体。

 [[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor blackColor],UITextAttributeTextColor, 
[UIFont fontWithName:@"ArialMT" size:16.0], UITextAttributeFont,nil]];