Reputation: 1470
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):
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?
Upvotes: 1
Views: 644
Reputation: 2261
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:
Upvotes: 4