Jonathan Tuzman
Jonathan Tuzman

Reputation: 13283

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.

Upvotes: 0

Views: 924

Answers (1)

Sagar Thummar
Sagar Thummar

Reputation: 2124

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

Upvotes: 3

Related Questions