Changing navigation title programmatically

Rising picture Rising · Aug 6, 2014 · Viewed 211k times · Source

I have a navigation bar with a title. When I double click the text to rename it, it actually says it's a navigation item, so it might be that.

I'm trying to change the text using code, like:

declare navigation bar as navagationbar here
button stuff {
    navigationbar.text = "title"
}

That's not my code obviously, just showing how it would work.

So whenever I press the button, I want the title to change.

Answer

drewag picture drewag · Aug 6, 2014

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"