Here is what I used previously,
var barButtonItem = UIBarButtonItem(image: backImgs, style: UIBarButtonItemStyle.plain, target: self, action: Selector(\"menu
In Swift 5
//For righter button item
let rightBtn = UIBarButtonItem(image: UIImage(named: "rightmenu"), style: .plain, target: self, action: #selector(onClickMethod))//Change your function name and image name here
self.navigationItem.rightBarButtonItem = rightBtn
//self.navigationItem.rightBarButtonItem = [rightBtn, anotherBtn] //If you want to add more buttons add like this
//For left bar button item
let leftBtn = UIBarButtonItem(image: UIImage(named: "rightmenu"), style: .plain, target: self, action: #selector(onClickMethod)) //Change your function name and image name here
self.navigationItem.leftItemsSupplementBackButton = true
self.navigationItem.leftBarButtonItem = leftBtn
//self.navigationItem.leftBarButtonItems = [leftBtn, anotherBtn] //If you want to add more buttons add like this
//This is your function name
@objc func onClickMethod() {
print("Left bar button item")
}
One line of code on Swift 3 for iOS 10.1:
navigationController?.navigationBar.topItem?.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: nil)
In Swift 3, you can add UIBarButtonItem like that,
let addButton = UIBarButtonItem(image:UIImage(named:"your_icon_name"), style:.plain, target:self, action:#selector(YourControllerName.buttonAction(_:)))
addButton.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = addButton
And handle button action like that,
func buttonAction(_ sender: UIBarButtonItem) {
}
Hope it helps.
create an extension for barbutton item.
extension UINavigationItem {
func addSettingButtonOnRight(){
let button = UIButton(type: .Custom)
button.setTitle("setting", forState: .Normal)
button.titleLabel?.font = UIFont.systemFontOfSize(15.0)
button.layer.cornerRadius = 5
button.backgroundColor = UIColor.grayColor()
button.frame = CGRect(x: 0, y: 0, width: 100, height: 25)
button.addTarget(self, action: #selector(gotSettingPage), forControlEvents: UIControlEvents.TouchUpInside)
let barButton = UIBarButtonItem(customView: button)
self.rightBarButtonItem = barButton
}
func gotSettingPage(){
}
}
And call it from viewDidLoad()
self.navigationItem.addSettingButtonOnRight()
ex:-
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Add", style: .plain, target: self, action: #selector(addTapped))
for Swift 4 add in viewDidLoad
:
navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: UIBarButtonSystemItem.add,
target: self,
action: #selector(addTransaction)
)