0

I am developing an application which will have multiple nested UIViewControllers. I have two views, one is the root view controller with a uibarbuttonitem, with is connected to another UIViewController.

The UIViewController which was segued to does not accept and UIButtons or UIBarButtonItems and I can't seem to set a title to it.

The Storyboard

I need to place a title and other UIElements in the UINavigationBar but nothing seems to work, and I did not find any solutions online.

The UINavigationBar does not even appear in the view's hierarchy.

Hierarchy

Thank you for any cooperation.

ItzAmmar
  • 53
  • 6
  • @vacawama i have edited the post. Please check again. – ItzAmmar May 11 '19 at 22:24
  • Try adding a UINavigationItem first. – Don May 11 '19 at 22:24
  • What did you tried so far? Can you show us, some code? – Mannopson May 11 '19 at 22:33
  • 2
    Set `self.title = "whatever"` in `viewDidLoad` in your view controller to set the title. Set right bar button with something like this: `self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Foo", style: .plain, target: self, action: #selector(handleRightBarButton))` – vacawama May 11 '19 at 22:41

1 Answers1

1

You're right. The Storyboard layout is inconsistent and confusing in the case of ViewControllers in the NavigationController stack. The first one offers direct access to the NavigationItem but later ones don't. I suppose that is because there is only one NavigationItem and it needs to be updated dynamically as the ViewControllers are pushed and popped.

The way to deal with this is to do it in code. When a ViewController is pushed, its title property is used to set the title on the navigation bar. So, in each of your ViewControllers that are in a NavigationController's stack, set its title in viewDidLoad:

self.title = "titleForThisVC"

For the rightBarButton, you add it programmatically as well. If this is your @IBAction for the button:

@objc func handleRightBarButton() {
    print("right button")
}

then you'd add the button like this (again in viewDidLoad):

self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Foo", style: .plain,
     target: self, action: #selector(handleRightBarButton))

One last gotcha for UITabBarControllers

If your NavigationControllers are the children of a UITabBarController, then the title that is used in the tab bar will pick up the title from the first ViewController in the stack as set by the code, but only after that tab has first been accessed. To get around this, the title property should also be set for the top ViewControllers in the Attributes Inspector in Interface Builder

vacawama
  • 150,663
  • 30
  • 266
  • 294