iOS rightBarButtonItem on UINavigationController in swift

Marcone picture Marcone · Jun 23, 2015 · Viewed 30.4k times · Source

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.

Answer

liushuaikobe picture liushuaikobe · Jun 23, 2015

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_