Swift 3.0 Adding a Right Button to Navigation Bar
You say you added a UINavigationBar
to your view controller via storyboard, but looking at the code you provided there is no outlet connection to your navigation bar in IB.
In order to access self.navigationItem
your view controller must be embedded in a UINavigationController
or be part of a hierarchy which is. Unless you have a need for a custom navigation bar on an individual view controller, I suggest removing that from Interface Builder, then making sure either the view controller in question is embedded in a UINavigationController
or it is being pushed onto the navigation stack from another controller which is embedded in a navigation controller and then you should see your UIBarButtonItem
.
let rightBarButtonItem = UIBarButtonItem.init(image: UIImage(named: "EditImage"), style: .done, target: self, action: #selector(ViewController.call_Method))
self.navigationItem.rightBarButtonItem = rightBarButtonItem
Firstly, you need to connect you navigation bar to an IBOutlet so that you can refer to it in your code. After that, this code should work:
let navigationItem = UINavigationItem(title: "Title")
navigationItem.rightBarButtonItem = self.addButton
navigationItem.hidesBackButton = true
self.navigationBar.pushItem(navigationItem, animated: false)
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:)))