Swift 3.0 Adding a Right Button to Navigation Bar

Kevin picture Kevin · Jul 13, 2017 · Viewed 50.3k times · Source

I have added a navigation bar to the top of a view controller. I am trying to control whether a button is visible based a condition, but I am having trouble adding the button. So far I have,

var addButton: UIBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))

override func viewDidLoad() {
    super.viewDidLoad()

    let boool = true
    if boool {
        self.navigationItem.rightBarButtonItem = self.addButton
    }
    else {
        self.navigationItem.rightBarButtonItem = nil
    }
}

func addTapped(sender: AnyObject) {
    print("hjxdbsdhjbv")
}

I believe it is not working properly because I have added a navigation bar into the VC, instead of using a navigation controller and working with the bar there. I was wondering if there was a way to work with this navigation bar.

Answer

Mannopson picture Mannopson · Jul 13, 2017

It’s simple. Put this line of code to the viewDidLoad:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .done, target: self, action: #selector(addTapped))

Updated for Swift 4 or later:

A custom function:

@objc func action(sender: UIBarButtonItem) {
    // Function body goes here
}

(Custom) Right bar button item:

self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "some_text", style: .done, target: self, action: #selector(self.action(sender:)))

(Custom) Left bar button item:

self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "some_text", style: .done, target: self, action: #selector(self.action(sender:)))

Also you can add a system bar button items something like this: UIBarButtonItem.SystemItem Defines system-supplied images for bar button items: .add, .done, .cancel, .edit, .save, .compose, .reply, .organize and more.

(System) Right bar button item:

self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.action(sender:)))

(System) Left bar button item:

self.navigationItem.leftBarButtonItem = UIBarButtonItem.init(barButtonSystemItem: UIBarButtonItem.SystemItem.add, target: self, action: #selector(self.action(sender:)))