简体   繁体   中英

UIBarButtonItems won't appear in Navigation Bar

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?

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:

导航项目

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM