iOS rightBarButtonItem on UINavigationController in swift

34.4k views Asked by At

I'm trying to put a rightBarButtonItem on a second view controller of an UINavigationViewController stack.

I'm creating and setting the button in viewDidLoad of the view controller that I want to show. My actual code looks like this:

override func viewDidLoad() {
    super.viewDidLoad()
    menu_button_ = UIBarButtonItem(image: UIImage(named: "menu"),
        style: UIBarButtonItemStyle.Plain ,
        target: self, action: "OnMenuClicked:")

    self.navigationController!.navigationItem.rightBarButtonItem = menu_button_
}

What am I missing? The button doesn't appear.

4

There are 4 answers

4
liushuaikobe On BEST ANSWER

You should set the menu_button_ as the rightBarButtonItem of your viewController rather than the navigationController.

Try

self.navigationItem.rightBarButtonItem = menu_button_

instead of

self.navigationController!.navigationItem.rightBarButtonItem = menu_button_
0
Abhishek Sharma On

try with following code. it works for me.

let homeButton : UIBarButtonItem = UIBarButtonItem(title: "LeftButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")

let logButton : UIBarButtonItem = UIBarButtonItem(title: "RigthButtonTitle", style: UIBarButtonItemStyle.Plain, target: self, action: "")

self.navigationItem.leftBarButtonItem = homeButton
self.navigationItem.rightBarButtonItem = logButton

And if you want to settle out custom image then please check with apple guidelines on below link.

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1

0
Naresh On

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

//This is your function
@objc func onClickMethod() {
    print("Left bar button item")
}
1
Dhiman Ranjit On

Create an extension of UINavigationItem like -

extension UINavigationItem {
    func addSettingButtonOnRight(){
        let button = UIButton(type: .custom)
    button.setTitle("setting", for: .normal)
    button.titleLabel?.font = UIFont.systemFont(ofSize: 15.0)
    button.layer.cornerRadius = 5
    button.backgroundColor = .gray
    button.frame = CGRect(x: 0, y: 0, width: 100, height: 25)
    button.addTarget(self, action: #selector(gotSettingPage), for: UIControlEvents.touchUpInside)
    let barButton = UIBarButtonItem(customView: button)

        self.rightBarButtonItem = barButton
    }

    @objc func gotSettingPage(){

    }
}

And call it from viewDidLoad() like -

self.navigationItem.addSettingButtonOnRight()