简体   繁体   中英

Swift: Trouble adding toolbar buttons for UINavigationController toolbar

I have the following viewDidLoad override in my subclass of UIViewController that's embedded in a Navigation Controller. I have un-hidden the toolbar, and when I run, the toolbar is there (which confirms that I am inside a navigation controller and that I'm addressing it correctly), but I can't get any buttons to show. What am I doing wrong here?

override func viewDidLoad() {
    super.viewDidLoad()

    var buttons = [UIBarButtonItem]()
    for title in buttonTitleArray {
        let plainButton = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(self.setContentMode(_:)))
        let systemButton = UIBarButtonItem(barButtonSystemItem: .play, target: self, action: #selector(self.setContentMode(_:)))
        buttons.append(plainButton)
        buttons.append(systemButton)
    }
    self.navigationController?.toolbarItems = buttons
    self.navigationController?.isToolbarHidden = false
}

I've tried adding the buttons using self.navigationController?.setToolbarItems(buttons, animated: false) but that doesn't work either.

Please try below code to display toolbar buttons on view:-

    var items = [UIBarButtonItem]()

    //Custom Button
    let plainButton = UIBarButtonItem(title: "Test", style: .Plain, target: self, action: #selector(self.customButtonTapped))
    items.append(plainButton)

    //Add Flexible space between buttons
    let flexibalSpace = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: self, action: nil)
    items.append(flexibalSpace)

    //Toolbar system button
    let systemButton = UIBarButtonItem(barButtonSystemItem: .Play, target: self, action: #selector(self.systemButtonTapped))
    items.append(systemButton)

    self.toolbarItems = items //Display toolbar items.
    self.navigationController?.toolbarHidden = false

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