UINavigationBar.appearance()。titleTextAttributes = [NSForegroundColorAttributeName不起作用

时间:2016-11-11 19:56:06

标签: ios colors uinavigationbar swift3

我正试图在我的UINavigationBar AppDelegate.swift中设置标题颜色,就像这样 -

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    UINavigationBar.appearance().barTintColor = UIColor(red: 26.0/255.0, green: 188.0/255.0, blue: 156.0/255.0, alpha: 1.0)
    UINavigationBar.appearance().tintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.white]
    UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName: UIFont(name: "Pacifico", size: 24)!]

    // Turquoise color rgba(26, 188, 156,1.0)

    return true
}

但它不起作用。结果看起来像this 为什么这不起作用?谢谢!

4 个答案:

答案 0 :(得分:6)

您将最初使用颜色设置的titleTextAttributes值覆盖为仅包含字体的新值。

您应该合并属性,然后立即设置它们:

编辑:Swift 4

let color = UIColor.white
let font = UIFont(name: "Pacifico", size: 24)!

let attributes: [NSAttributedStringKey: AnyObject] = [
        NSAttributedStringKey.font: font,
        NSAttributedStringKey.foregroundColor: color
    ]

UINavigationBar.appearance().titleTextAttributes = attributes

Swift 3

let color = UIColor.white
let font = UIFont(name: "Pacifico", size: 24)!

let attributes: [String: AnyObject] = [
    NSFontAttributeName: font,
    NSForegroundColorAttributeName: color
]

UINavigationBar.appearance().titleTextAttributes = attributes

答案 1 :(得分:2)

斯威夫特4:

对于NavigationBar背景颜色:

UINavigationBar.appearance().barTintColor = UIColor(red: 50/255, green: 90/255, blue: 150/255, alpha: 1)

对于NavigationBar标题颜色和字体:

let attrs = [
    NSAttributedStringKey.foregroundColor: UIColor.red,
    NSAttributedStringKey.font: UIFont(name: "Georgia-Bold", size: 24)!
]

UINavigationBar.appearance().titleTextAttributes = attrs

参考:here

答案 2 :(得分:0)

将代码放入AppDelegate文件

let appTitlecolor = UIColor(red: 155.0/255.0, green: 204.0/255.0, blue: 67.0/255.0, alpha: 1.0)

UINavigationBar.appearance().titleTextAttributes = [NSFontAttributeName:UIFont(name: "Helvetica", size: 20)!, NSForegroundColorAttributeName: appTitlecolor]

答案 3 :(得分:0)

对于Swift 4.2

let color = UIColor.white
let font = UIFont(name: "Pacifico", size: 24)!

let attributes = [
  NSAttributedString.Key.font: font,
  NSAttributedString.Key.foregroundColor: color
]

UINavigationBar.appearance().titleTextAttributes = attributes