how to change navigationitem title color

I think all day to change the navigation Bar title color, but it doesn't work. this is my code:

var user: User? {
    didSet {
        navigationItem.title = user?.name

         observeMessages()
    }
}

I use didSet to show the title on the navigation title.


Solution 1:

Add this in your code . .

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

Keeping all the other attributes of the title: If you just want change the color you could do like this:

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

Solution 2:

The title color of Navigation Bar can be changed in Storyboard.

Go to Attributes inspector of Navigation Controller > Navigation Bar and set the desired color in Title Color menu.


enter image description here

Solution 3:

Solution for iOS 13

To customize the appearance of a navigation bar you need to use UINavigationBarAppearance:

let appearance = UINavigationBarAppearance()
appearance.titleTextAttributes = [.foregroundColor: UIColor.red]
appearance.largeTitleTextAttributes = [.foregroundColor: UIColor.red]

navigationItem.standardAppearance = appearance
navigationItem.scrollEdgeAppearance = appearance

Solution 4:

Swift 4

set this first

navigationController?.navigationBar.barStyle = .default

then one of those should work

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

or

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

Swift 5

navigationBar.largeTitleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]

or

navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.red]