Twitter khuong291
Twitter khuong291

Reputation: 11702

Add bar button to navigation bar programatically

I want to when I click to the button, it will present a navigation bar. But the button that I add, it doesn't show.

Here is my code:

@IBAction func handleCommentsCountButtonTap(sender: AnyObject) {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let loginVC = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as! LoginViewController
    let navigation = UINavigationController(rootViewController: loginVC)
    let backButton = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Plain, target: navigation, action: "backAction")
    navigation.navigationItem.leftBarButtonItem = backButton

    self.presentViewController(navigation, animated: true, completion: nil)
  }

Upvotes: 1

Views: 187

Answers (2)

Swapnil Luktuke
Swapnil Luktuke

Reputation: 10475

navigationItem is a UIViewController property and Apple's documentation for navigationItem says

Created on-demand so that a view controller may customize its navigation appearance.

Which means the correct place to set navigation item buttons is in respective view controllers. So you should be setting the navigation item buttons on

    loginVC.navigationItem.leftBarButtonItem = backButton

or directly in LoginViewController's viewDidLoad as

    self.navigationItem.leftBarButtonItem = backButton

The suggested comment and answer using topItem works because topItem indirectly gives access to the top view controller's navigation item.

Upvotes: 1

Caleb
Caleb

Reputation: 5626

Adding answer since I could not find a duplicate of this question.

You can use this:

navigation.navigationBar.topItem.leftBarButtonItem = backButton

Upvotes: 1

Related Questions