如何更改navigationitem标题颜色

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

var user: User? { didSet { navigationItem.title = user?.name observeMessages() } } 

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

在您的代码中添加它。 。

 let textAttributes = [NSForegroundColorAttributeName:UIColor.red] navigationController?.navigationBar.titleTextAttributes = textAttributes 

SWIFT 4:

 let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.red] navigationController?.navigationBar.titleTextAttributes = textAttributes 

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

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


在此处输入图像描述

先设定这个

 navigationController?.navigationBar.barStyle = .default 

那么其中一个应该工作

 navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red] 

要么

 navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.red] 

如果您设置了用户,则调用didSet,也许您正在设置用户的名称变量并期望程序进入didSet。 尝试设置用户。

如果要在导航标题更改为用户名时更改文本颜色,只需调用此代码即可。

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

 var user: User? { didSet { navigationItem.title = user?.name } } override func viewDidLoad() { super.viewDidLoad() let newUser = User() newUser.name = "John Doe" user = newUser }