George B George B - 29 days ago 4
iOS Question

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName doesn't work

I am trying to set the title color in my

UINavigationBar
in my
AppDelegate.swift
, like this-

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
}


But it doesn't work. The result looks like this
Why isn't this working? Thanks!

par par
Answer

You're overwriting the titleTextAttributes value you set initially with the color to a new value that includes only the font.

You should combine your attributes and then set them at once:

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

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

UINavigationBar.appearance().titleTextAttributes = attributes