Changing Navigation Title Programmatically

Changing navigation title programmatically

You change the title by changing the title of the view controller being displayed:

viewController.title = "some title"

Normally this is done in view did load on the view controller:

override func viewDidLoad() {
super.viewDidLoad()
self.title = "some title"
}

However, this only works if you have your view controller embedded in a UINavigationController. I highly recommend doing this instead of creating a navigation bar yourself. If you insist on creating a navigation bar yourself, you can change the title by doing:

navigationBar.topItem.title = "some title"

Changing Nav Bar title programmatically

self.navigationController.navigationBar.topItem.title = @"YourTitle";

Set title of navigation bar

For Swift 3:

If you want to set just the navigation title without using a UINavigationController then make an outlet of the navigation item as

 @IBOutlet weak var navItem: UINavigationItem!

and then in viewDidLoad() write

navItem.title = "ANY TITLE"

How to set the title of a Navigation Bar programmatically?

In your UIViewController

self.navigationItem.title = @"The title";

UINavigationBar - Set title programmatically?

I've set the title programmatically using code something like this:

navBar.topItem.title = @"title";

where navBar is declared as an IBOutlet UINavigationBar linked to the navigation bar in interface builder. This worked in my app; however, I was not using a tab bar.

If navBar.topItem is the tab bar item, I don't see a way for you to change the title that appears on the navigation bar without also changing the title on the tab bar item, since the navBar's topItem and the tab bar item is the same object.

how to change navigationitem title color

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
}


Related Topics



Leave a reply



Submit