iPhone 导航栏标题文本颜色

发布于 2024-07-14 18:26:13 字数 163 浏览 6 评论 0原文

iOS 导航栏标题颜色默认为白色。 有没有办法将其更改为不同的颜色?

我知道使用图像的 navigationItem.titleView 方法。 由于我的设计能力有限,未能达到标准的光泽度,所以我更喜欢更改文本颜色。

任何见解将不胜感激。

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

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

Any insight would be much appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

香草可樂 2024-07-21 18:26:13

现代方法

现代方法,对于整个导航控制器......在加载导航控制器的根视图时执行一次。

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

不过,这似乎并没有对后续的观点产生影响。

经典方法

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

您需要使用 UILabel 作为 navigationItemtitleView

标签应该:

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

将标签文本颜色设置为任何自定义颜色你确实想要一种不会导致文本融入阴影的颜色,这会很难阅读,

但我想出的值最终太简单了。它们不是 Apple 选择的:)

如果您想验证这一点,请将此代码放入 Apple 的导航栏示例。 这会将文本替换为黄色标签。 除了颜色之外,这应该与 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 的回答。 我的代码显示了效果,但他的代码提供了一种更简单的方法来将其放置在现有视图控制器上。

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):

You need to use a UILabel as the titleView of the navigationItem.

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 (UITextAlignmentCenter for older SDKs).

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. :)

If you want to verify this, drop this code into initWithNibName:bundle: in PageThreeViewController.m of 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.

- (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.

尬尬 2024-07-21 18:26:13

我知道这是一个相当古老的线程,但我认为对于新用户来说,了解 iOS 5 带来了用于建立标题属性的新属性会很有用。

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

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

例如像这样:

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

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];

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.

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

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

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];
人生百味 2024-07-21 18:26:13

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

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

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

navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};
贵在坚持 2024-07-21 18:26:13

根据 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];
}

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

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

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.

等风来 2024-07-21 18:26:13

对于 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 以获取可以设置的各种文本属性。

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

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.

影子的影子 2024-07-21 18:26:13

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

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

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

self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor greenColor] forKey:NSForegroundColorAttributeName];
只等公子 2024-07-21 18:26:13

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

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

结果为:

在此处输入图像描述

To keep the question up-to-date, I'll add Alex R. R. solution, but in 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

月棠 2024-07-21 18:26:13

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

Swift Version

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

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

In ViewDidload

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

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

2.To make NavigationBar background becomes Image (for example : 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])

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)

I hope I can help!:D

快乐很简单 2024-07-21 18:26:13

方法一,在IB中设置:

在此处输入图像描述

方法2,一行代码:

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

Method 1, set it in IB:

enter image description here

Method 2, one line of code:

navigationController?.navigationBar.barTintColor = UIColor.blackColor()
失而复得 2024-07-21 18:26: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

The solution by tewha works well if you are trying to change the color on a page, but I want to be able to change the color on every page. I made some small modifications so that it would work for all pages on a 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
○愚か者の日 2024-07-21 18:26:13

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

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

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).

 [[UINavigationBar appearance] setTitleTextAttributes:
 [NSDictionary dictionaryWithObjectsAndKeys:
  [UIColor blackColor],UITextAttributeTextColor, 
[UIFont fontWithName:@"ArialMT" size:16.0], UITextAttributeFont,nil]];
流星番茄 2024-07-21 18:26:13

简短而甜蜜。

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

Short and sweet.

[[[self navigationController] navigationBar] setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]}];
樱花坊 2024-07-21 18:26:13

在任何视图控制器 viewDidLoad 或 viewWillAppear 方法中使用以下代码。

- (void)viewDidLoad
{
    [super viewDidLoad];

    //I am using UIColor yellowColor for an example but you can use whatever color you like   
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

    //change the title here to whatever you like
    self.title = @"Home";
    // Do any additional setup after loading the view.
}

Use the code below in any view controller viewDidLoad or viewWillAppear method.

- (void)viewDidLoad
{
    [super viewDidLoad];

    //I am using UIColor yellowColor for an example but you can use whatever color you like   
    self.navigationController.navigationBar.titleTextAttributes = @{NSForegroundColorAttributeName: [UIColor yellowColor]};

    //change the title here to whatever you like
    self.title = @"Home";
    // Do any additional setup after loading the view.
}
ぺ禁宫浮华殁 2024-07-21 18:26:13

这是我基于史蒂文斯的解决方案

唯一真正的区别是我根据文本长度进行了一些处理来调整位置,似乎与苹果的做法类似

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft), 0, 480,44)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.font = [UIFont boldSystemFontOfSize: 20.0f];
titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleLabel.textAlignment = ([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft);
titleLabel.textColor = [UIColor redColor];
titleLabel.text = self.title;
self.navigationItem.titleView = titleLabel;
[titleLabel release];

您可能需要根据您的字体大小调整 10 值

This is my solution based upon Stevens

Only real difference is I put some handling in for adjust the position if depending on the text length, seems to be similar to how apple do it

UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft), 0, 480,44)];
titleLabel.backgroundColor = [UIColor clearColor];
titleLabel.font = [UIFont boldSystemFontOfSize: 20.0f];
titleLabel.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
titleLabel.textAlignment = ([self.title length] < 10 ? UITextAlignmentCenter : UITextAlignmentLeft);
titleLabel.textColor = [UIColor redColor];
titleLabel.text = self.title;
self.navigationItem.titleView = titleLabel;
[titleLabel release];

You may want to adjust the 10 value depending on your font size

傲影 2024-07-21 18:26:13

斯威夫特 4 & 4.2版本:

 self.navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]

Swift 4 & 4.2 version:

 self.navigationController.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.green]
何必那么矫情 2024-07-21 18:26:13

我遇到了导航按钮将文本偏离中心的问题(当您只有一个按钮时)。 为了解决这个问题,我只是改变了我的框架大小,如下所示:

CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);

I ran into the problem with my nav buttons throwing the text out of center (when you only have one button). To fix that I just changed my frame size like so:

CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
拥醉 2024-07-21 18:26:13

我已经自定义了导航栏的背景图像和左按钮项目,并且灰色标题不适合背景。 然后我使用:

[self.navigationBar setTintColor:[UIColor darkGrayColor]];

将色调颜色更改为灰色。 现在标题是白色的! 这就是我想要的。

也希望能有所帮助:)

I've customized the navigationBar's background image and left button item, and the gray title not fit the background. Then I use:

[self.navigationBar setTintColor:[UIColor darkGrayColor]];

to change the tint color to gray. And the title is white now! That's what I want.

Hope to help also :)

旧人哭 2024-07-21 18:26:13

建议设置 self.title,因为在推送子导航栏或在选项卡栏上显示标题时会使用它。

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // create and customize title view
        self.title = NSLocalizedString(@"My Custom Title", @"");
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.text = self.title;
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor whiteColor];
        [titleLabel sizeToFit];
        self.navigationItem.titleView = titleLabel;
        [titleLabel release];
    }
}

It's recommended to set self.title as this is used while pushing child navbars or showing title on tabbars.

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // create and customize title view
        self.title = NSLocalizedString(@"My Custom Title", @"");
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        titleLabel.text = self.title;
        titleLabel.font = [UIFont boldSystemFontOfSize:16];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.textColor = [UIColor whiteColor];
        [titleLabel sizeToFit];
        self.navigationItem.titleView = titleLabel;
        [titleLabel release];
    }
}
明天过后 2024-07-21 18:26:13

这是一个相当老的线程,但我想提供为 iOS 7 及更高版本设置导航栏标题的颜色、大小和垂直位置的答案

颜色和大小

 NSDictionary *titleAttributes =@{
                                NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                NSForegroundColorAttributeName : [UIColor whiteColor]
                                };

垂直位置

[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-10.0 forBarMetrics:UIBarMetricsDefault];

设置标题并分配属性字典

[[self navigationItem] setTitle:@"CLUBHOUSE"];
self.navigationController.navigationBar.titleTextAttributes = titleAttributes;

This is a pretty old thread but I think of providing answer for setting Color, Size and Vertical Position of Navigation Bar Title for iOS 7 and above

For Color and Size

 NSDictionary *titleAttributes =@{
                                NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
                                NSForegroundColorAttributeName : [UIColor whiteColor]
                                };

For Vertical Position

[[UINavigationBar appearance] setTitleVerticalPositionAdjustment:-10.0 forBarMetrics:UIBarMetricsDefault];

Set Title and assign the attributes dictionary

[[self navigationItem] setTitle:@"CLUBHOUSE"];
self.navigationController.navigationBar.titleTextAttributes = titleAttributes;
梦境 2024-07-21 18:26:13

这在 Swift 中对我有用:

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

This works for me in Swift:

navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.white]
_失温 2024-07-21 18:26:13
self.navigationItem.title=@"Extras";
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:21], NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];
self.navigationItem.title=@"Extras";
[self.navigationController.navigationBar setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"HelveticaNeue" size:21], NSFontAttributeName,[UIColor whiteColor],UITextAttributeTextColor,nil]];
孤者何惧 2024-07-21 18:26:13

像这样使用方向支持

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
[view setBackgroundColor:[UIColor clearColor]];
[view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];

UILabel *nameLabel = [[UILabel alloc] init];
[nameLabel setFrame:CGRectMake(0, 0, 320, 40)];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setFont:[UIFont boldSystemFontOfSize:17]];
[nameLabel setText:titleString];
[nameLabel setTextAlignment:UITextAlignmentCenter];
[view addSubview:nameLabel];
[nameLabel release];
self.navigationItem.titleView = view;
[view release];

Use like this for Orientation support

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,40)];
[view setBackgroundColor:[UIColor clearColor]];
[view setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight ];

UILabel *nameLabel = [[UILabel alloc] init];
[nameLabel setFrame:CGRectMake(0, 0, 320, 40)];
[nameLabel setBackgroundColor:[UIColor clearColor]];
[nameLabel setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin |UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleLeftMargin];
[nameLabel setTextColor:[UIColor whiteColor]];
[nameLabel setFont:[UIFont boldSystemFontOfSize:17]];
[nameLabel setText:titleString];
[nameLabel setTextAlignment:UITextAlignmentCenter];
[view addSubview:nameLabel];
[nameLabel release];
self.navigationItem.titleView = view;
[view release];
鹿童谣 2024-07-21 18:26:13

要设置标题的字体大小,我使用了以下条件..也许对任何人都有帮助

if ([currentTitle length]>24) msize = 10.0f;
    else if ([currentTitle length]>16) msize = 14.0f;
    else if ([currentTitle length]>12) msize = 18.0f;

to set font size of title i have used following conditions.. maybe helpfull to anybody

if ([currentTitle length]>24) msize = 10.0f;
    else if ([currentTitle length]>16) msize = 14.0f;
    else if ([currentTitle length]>12) msize = 18.0f;
回眸一笑 2024-07-21 18:26:13

使用新的 iOS 7 文本属性和现代目标 c 来减少噪音,对 Alex RR 的帖子进行了更新:

NSShadow *titleShadow = [[NSShadow alloc] init];
titleShadow.shadowColor = [UIColor blackColor];
titleShadow.shadowOffset = CGSizeMake(-1, 0);
NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                            NSShadowAttributeName:titleShadow};

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];

An update to Alex R. R.'s post using the new iOS 7 text attributes and modern objective c for less noise:

NSShadow *titleShadow = [[NSShadow alloc] init];
titleShadow.shadowColor = [UIColor blackColor];
titleShadow.shadowOffset = CGSizeMake(-1, 0);
NSDictionary *navbarTitleTextAttributes = @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                            NSShadowAttributeName:titleShadow};

[[UINavigationBar appearance] setTitleTextAttributes:navbarTitleTextAttributes];
电影里的梦 2024-07-21 18:26:13

我确实相信设置 UINavigationBar 颜色的正确方法是:

NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil];
self.titleTextAttributes = attributes;

上面编写的代码是 UINavigationBar 上的子类,显然也无需子类化即可工作。

I do believe proper way to set the colour of UINavigationBar is:

NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor redColor],UITextAttributeTextColor, nil];
self.titleTextAttributes = attributes;

Code above is written is subclass on UINavigationBar, obviously works without subclassing as well.

吃不饱 2024-07-21 18:26:13

这是缺失的事情之一。 最好的选择是创建自己的自定义导航栏,添加文本框,并以这种方式操纵颜色。

This is one of those things that are missing. Your best bet is to create your own custom Navigation Bar, add a text box, and manipulate the color that way.

往昔成烟 2024-07-21 18:26:13

在遇到与我们在导航栏中插入按钮时移动的标签相同的问题(与其他问题一样)之后(在我的例子中,我有一个微调器,在加载日期时用按钮替换),上述解决方案不起作用对我来说,以下是有效的方法,并且始终将标签保持在同一位置:

- (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
    //CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
   CGRect frame = CGRectMake(0, 0, 180, 44);
    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];
    self.navigationItem.titleView = label;
    label.text = NSLocalizedString(@"Latest Questions", @"");
    [label sizeToFit];
}

return self;

After encountering the same problem (as others) of the label that moves when we insert a button in the navBar (in my case i have a spinner that i replace with a button when the date is loaded), the above solutions didn't work for me, so here is what worked and kept the label at the same place all the time:

- (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
    //CGRect frame = CGRectMake(0, 0, [self.title sizeWithFont:[UIFont boldSystemFontOfSize:20.0]].width, 44);
   CGRect frame = CGRectMake(0, 0, 180, 44);
    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];
    self.navigationItem.titleView = label;
    label.text = NSLocalizedString(@"Latest Questions", @"");
    [label sizeToFit];
}

return self;
会傲 2024-07-21 18:26:13

您应该调用 [label sizeToFit]; 设置文本以防止当其他按钮占据导航栏时标签在标题视图中自动重新定位时出现奇怪的偏移。

You should call [label sizeToFit]; after setting the text to prevent strange offsets when the label is automatically repositioned in the title view when other buttons occupy the nav bar.

谁与争疯 2024-07-21 18:26:13

可以在 appdelegate 文件中使用此方法,并且可以在每个视图中使用

+(UILabel *) navigationTitleLable:(NSString *)title
{
CGRect frame = CGRectMake(0, 0, 165, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = NAVIGATION_TITLE_LABLE_SIZE;
label.shadowColor = [UIColor whiteColor];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeTailTruncation;    
label.textAlignment = UITextAlignmentCenter;
[label setShadowOffset:CGSizeMake(0,1)]; 
label.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];

//label.text = NSLocalizedString(title, @"");

return label;
}

Can use this method in appdelegate file and can use at every view

+(UILabel *) navigationTitleLable:(NSString *)title
{
CGRect frame = CGRectMake(0, 0, 165, 44);
UILabel *label = [[[UILabel alloc] initWithFrame:frame] autorelease];
label.backgroundColor = [UIColor clearColor];
label.font = NAVIGATION_TITLE_LABLE_SIZE;
label.shadowColor = [UIColor whiteColor];
label.numberOfLines = 2;
label.lineBreakMode = UILineBreakModeTailTruncation;    
label.textAlignment = UITextAlignmentCenter;
[label setShadowOffset:CGSizeMake(0,1)]; 
label.textColor = [UIColor colorWithRed:51/255.0 green:51/255.0 blue:51/255.0 alpha:1.0];

//label.text = NSLocalizedString(title, @"");

return label;
}
一张白纸 2024-07-21 18:26:13

标题文本属性
显示栏标题文本的属性。

@property(nonatomic, 复制) NSDictionary *titleTextAttributes
讨论
您可以使用 NSString UIKit Additions Reference 中描述的文本属性键在文本属性字典中指定标题的字体、文本颜色、文本阴影颜色和文本阴影偏移量。

可用性
适用于 iOS 5.0 及更高版本。
申报于
UINavigationBar.h

titleTextAttributes
Display attributes for the bar’s title text.

@property(nonatomic, copy) NSDictionary *titleTextAttributes
Discussion
You can specify the font, text color, text shadow color, and text shadow offset for the title in the text attributes dictionary, using the text attribute keys described in NSString UIKit Additions Reference.

Availability
Available in iOS 5.0 and later.
Declared In
UINavigationBar.h

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文