Reputation: 10046
So I have a basic view controller with a navigation bar, this is view controller B, so I'm performing a segue to go here, and I'm trying to change the title like this:
override func viewDidLoad() {
debugPrint(self.selectedName)
super.viewDidLoad();
self.navigationItem.title = "A NEW TITLE"
}
But it doesn't do anything
Upvotes: 15
Views: 39443
Reputation:
Swift 4 / XCode 10
Add new NavigationBar ->
Drap and Drop it to your view
Press CTRL to add new Outlet Action
Example : @IBOutlet weak var main_navbar: UINavigationBar
in ViewController
class.
Then set the title : main_navbar.topItem?.title = "YOUR TITLE"
This solution worked for me, hope it does for you too. - rust
Upvotes: 4
Reputation: 6650
There are plenty of methods which you can follow to achieve this. Here is few of those.
First things first.
If you are ready to "Embed in" a navigation controller or if you have already one then you can access that using following code.
self.navigationController?.navigationBar.topItem?.title = "Your Title"
Now for more customization:
UINavigationBar
object on ViewController scene and add constraints to it.Make an outlet of newly placed UINavigationBar
like as follows -
@IBOutlet weak var orderStatusNavigationbar: UINavigationBar!
Now set the title using the outlet.
orderStatusNavigationbar.topItem?.title = "Your Title"
All this above code are in Swift 3 but will work on lower versions of Swift also(atleast on Swift 2.0)
Hope this helped.
Upvotes: 12
Reputation: 2139
To set Title on NavigationBar simply we can do by below code
self.title = "Your Title"
Upvotes: 19
Reputation: 921
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"
Upvotes: 16
Reputation: 5957
Ok, So you need to embed the whole thing in a Navigation Controller first, and then make that navigation controller as the initial controller.
Select your storyboard, click the first controller then click this -
Then you remove the navigation bar you set(put) over the last controller named "title".
The reason this didnt work, as you are trying to change the title of the navigation controller's navigation bar, but it doesnt have it, hence it cant change it.
Upvotes: 3