20

I'm trying to set title of Navigation Bar in Swift, I set Tab Bar and in Navigation Bar nothing is showing, no button, no title, nothing. I used some code but it's not working while I use Tab Bar, and when I deleted Tab Bar, code is working and everything is ok with Navigation Bar, title is showing and buttons are showing.

Code that I used for title is:

override func viewDidLoad() {
    super.viewDidLoad()

    self.navigationItem.title = "My Title"

}

And in Main.storyboard I connected Navigation Controller with Tab Bar Controller, as in picture.

enter image description here

So, how to fix this ? The problem is that Navigation Bar is not working while using Tab Bar.

Emm
  • 1,963
  • 2
  • 20
  • 51
  • 1
    You have the navigation controller and the tab bar controller the wrong way around. The tab bar should be the root. Then each tab should have a navigation controller. This will give you the standard controls that come with a tab bar and setting the title will be easier. – Fogmeister Nov 14 '15 at 10:56
  • 1
    When combining tab bar controllers and navigation controllers, the root controller should be a tab bar controller and each tab should have its own nav controller. See http://stackoverflow.com/a/26153273/1630618 – vacawama Nov 14 '15 at 10:56

3 Answers3

31

Since the Tab Bar is actually the Root View Controller of the Navigation Bar, you need to set the UITabBarController's title instead in the viewWillAppear function so that it happens every time you switch tabs:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBarController?.navigationItem.title = "My Title"
    self.tabBarController?.navigationItem.leftBarButtonItem = settingsButton //This is the IBOutlet variable that you previously added
}

But a better way to do it would actually be to have it the other way around, like so

Correct view hierarchy

You should hook up a UINavigationController for each child of the UITabBarController, as it is more correct semantically, and simpler to maintain.

kabiroberai
  • 2,930
  • 19
  • 34
10

Your question is unclear, if the code you presented is from UIViewController that is kept inside UINavigationController and navigationBar is shown you can simply use:

override func viewDidLoad() {
    super.viewDidLoad()
    self.title = "My Title"
}
katleta3000
  • 2,484
  • 1
  • 18
  • 23
1

In UINavigationController Class Reference Apple wrote this:

init(rootViewController: UIViewController)
Parameters rootViewController
The view controller that resides at the bottom of the navigation stack. This object cannot be an instance of the UITabBarController class.

But you can do it if you insisted.But in this case , your ViewControllers of tabbarController all shared the same title,which is the title of tabbarController.

A better way to do it is to give each of tabbarController's viewControllers a NavigationViewController.

wj2061
  • 6,778
  • 3
  • 36
  • 62