1

I have a UIViewContoller that is intentionally NOT embedded in a UINavigationController and I want to add custom buttons in the navigation area. I believe the code I've written should work because it follows the suggested method I found on several threads about UIBarButtonItem (these mostly have to do with styling though). Here's my code:

override func viewDidLoad() {
    super.viewDidLoad()

    let settingsButton = UIBarButtonItem(title: "Settings", style: .Plain, target: self, action: #selector(self.segueToSettings(_:)))
    let saveToLogButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(self.logThisLift(_:)))
    let viewLogButton = UIBarButtonItem(title: "Log", style: .Plain, target: self, action: #selector(self.segueToLog(_:)))

    self.navigationItem.leftBarButtonItem = settingsButton
    self.navigationItem.rightBarButtonItems = [viewLogButton, saveToLogButton]
  }

and here's the result (with the View hierarchy visible too):

enter image description here

I thought perhaps I needed to add Bar Button Items in the Storyboard but that would seem to defeat the purpose of doing it in code like I'm trying to do.

I've tried debugging the view hierarchy as well and I don't see them there.

Does anybody know why these wouldn't be appearing?

1
  • try adding it in viewDidAppear() rather then view did load and see what happens :)
    – Konsy
    Jul 18, 2016 at 19:00

1 Answer 1

4

In your code you use self.navigationItem but you don't have a navigation item since your controller is not embedded in navigation controller.

You already added a navigation bar but you need to add a navigation item.

You have to drag a navigation item to the navigation bar and then binding to the code (via an outlet). It should be like this after that:

@IBOutlet weak var navItem: UINavigationItem!

And then you can say:

self.navItem.leftBarButtonItem = settingsButton
self.navItem.rightBarButtonItems = [viewLogButton, saveToLogButton]

You should see it in the document outline like this:

Navigation item

1
  • Thanks, just tried it, works really well, have better understanding toward nav bar now. Oct 6, 2018 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.