ios - 如何更改导航项标题颜色

标签 ios swift

我整天想着改变导航栏标题的颜色,但不管用。这是我的代码:

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

SWIFT 4.2+:

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

保留标题的所有其他属性: 如果你只想改变颜色,你可以这样做:

if var textAttributes = navigationController?.navigationBar.titleTextAttributes {
    textAttributes[NSAttributedString.Key.foregroundColor] = UIColor.red
    navigationController?.navigationBar.titleTextAttributes = textAttributes
}

关于ios - 如何更改导航项标题颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43706103/

相关文章:

ios - 使用 Google Maps SDK 的哪个方法,例如 MapKit 的 struct MKCooperativeRegion

iphone - 移动 tableview 时裁剪 UITableviewcell

ios - 如何使用 swift 下载和共享 pdf 文件

iOS 确保栏按钮项目在 iPhone SE 的 UINavigationBar 中显示为全尺寸

swift 从终端抛出 python 错误

ios - 在 iOS 上打开时得到 -1,为什么?

ios - 即使在导入 MapKit 后仍使用未声明的类型 'MKMapView'

ios - 将NSUserDefaults放在哪里存储注释

ios - DispatchQueue.main.asyncAfter 带开/关开关

swift - 如何检查inf? swift xcode7