How can I change the NavBar title text color in swift 4?

Viewed 15602

When developing in swift 3 I was used to write:

UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]

putting this in AppDelegate would change all the UINavbars' title color to orange.

Now I want to do the same with Swift 4 and iOS 11.

8 Answers

App delegate swift 4.2

 UINavigationBar.appearance().barTintColor = UIColor.white
 UINavigationBar.appearance().tintColor = UIColor(hex: 0xED6E19)
 UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor(hex: 0xED6E19)]

Swift 4 implementation for both large and regular titles:

extension UINavigationController {
    func setTitleForgroundTitleColor(_ color: UIColor) {
        self.navigationBar.titleTextAttributes = [NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): color]
    }

    func setLargeTitleColor(_ color: UIColor) {
        self.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey(rawValue: NSAttributedStringKey.foregroundColor.rawValue): color]
    }

    func setAllTitleColor(_ color: UIColor) {
        setTitleForgroundTitleColor(color)
        setLargeTitleColor(color)
    }
}

You can change the navigation bar title color by using this code

navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]

Swift 4.2

fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
        guard let input = input else { return nil }
        return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}

Usage

   // Set Navigation bar Title color

UINavigationBar.appearance().titleTextAttributes = convertToOptionalNSAttributedStringKeyDictionary([NSAttributedString.Key.foregroundColor.rawValue : UIColor.white])

For Swift 5 if Someone is Looking around like I was :

self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor(displayP3Red: 84/255, green: 93/255, blue: 118/255, alpha: 1)]
Related