如何更改navigationitem标题颜色

熊天宇*_*熊天宇 50 ios swift

我想整天都要更改导航栏标题颜色,但它不起作用.这是我的代码:

var user: User? {
    didSet {
        navigationItem.title = user?.name

         observeMessages()
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用didSet在导航标题上显示标题.

roy*_*roy 137

在您的代码中添加它..

let textAttributes = [NSForegroundColorAttributeName:UIColor.red]
navigationController?.navigationBar.titleTextAttributes = textAttributes
Run Code Online (Sandbox Code Playgroud)

SWIFT 4:

let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.red]
navigationController?.navigationBar.titleTextAttributes = textAttributes
Run Code Online (Sandbox Code Playgroud)

SWIFT 4.2+:

let textAttributes = [NSAttributedString.Key.foregroundColor:UIColor.red]
navigationController?.navigationBar.titleTextAttributes = textAttributes
Run Code Online (Sandbox Code Playgroud)


Tza*_*zar 30

可以在Storyboard中更改导航栏的标题颜色.

转到导航控制器 > 导航栏的属性检查器,并在" 标题颜色"菜单中设置所需的颜色.


在此输入图像描述


Mo *_*ani 18

适用于 iOS 13 的解决方案

要自定义导航栏的外观,您需要使用UINavigationBarAppearance

let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.red]
appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.red]

navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance
Run Code Online (Sandbox Code Playgroud)

  • 任何因为 iOS15 来到这里的人,这是正确的答案:) 我添加了 `largeTitleTextAttributes` 并且标题已更改。 (5认同)

小智 9

斯威夫特4

首先设置这个

navigationController?.navigationBar.barStyle = .default
Run Code Online (Sandbox Code Playgroud)

那么其中之一应该工作

navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red]
Run Code Online (Sandbox Code Playgroud)

要么

navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red]
Run Code Online (Sandbox Code Playgroud)

迅捷5

navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
Run Code Online (Sandbox Code Playgroud)

要么

navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]
Run Code Online (Sandbox Code Playgroud)


Adr*_*ana 7

在目标 C 中:

[UINavigationBar appearance] setTitleTextAttributes: 
    [NSDictionary dictionaryWithObjectsAndKeys: 
        [UIColor blackColor], NSForegroundColorAttributeName, 
           [UIFont fontWithName:@"ArialMT" size:16.0], NSFontAttributeName,nil]];
Run Code Online (Sandbox Code Playgroud)


Chu*_*y47 6

对于 iOS 13,您必须更改外观属性中的颜色,对于较旧的 iOS 版本,您可以直接在导航栏属性中进行更改。

if #available(iOS 13.0, *) {
    navigationController?.navigationBar.standardAppearance.titleTextAttributes = [.foregroundColor: UIColor.white]
} else {
    navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.white]
}
Run Code Online (Sandbox Code Playgroud)