COSMO BAKER
COSMO BAKER

Reputation: 457

Unable to Add Bar Button Item Programatically

func myPlaceViewMoreWasPressed() {
    print("myPlaceViewMore was pressed")

    let vc = MyPlacesViewController(nil)
    let nav = UINavigationController(rootViewController: vc)
    let dismissButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(dismissButtonWasPressed))
    nav.navigationItem.leftBarButtonItem = dismissButton

    self.present(nav, animated: true, completion: nil)
}

Should be very straightforward... instantiate a ViewController, contain it in a navigation controller, init a UIBarButtonItem and set it the leftBarButtonItem of the nav. I've also tried it like this:

func myPlaceViewMoreWasPressed() {
    print("myPlaceViewMore was pressed")

    let vc = MyPlacesViewController(nil)
    let nav = UINavigationController(rootViewController: vc)
    let dismissButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(dismissButtonWasPressed))
    nav.navigationItem.setLeftBarButton(dismissButton, animated: true)

    self.present(nav, animated: true, completion: nil)
}

But the button will not appear.

Upvotes: 0

Views: 151

Answers (1)

rmaddy
rmaddy

Reputation: 318934

You need to update the navigationItem of the view controller, not the navigation controller. I would do that before setting the view controller as the root controller.

func myPlaceViewMoreWasPressed() {
    print("myPlaceViewMore was pressed")

    let vc = MyPlacesViewController(nil)
    let dismissButton = UIBarButtonItem.init(title: "Dismiss", style: .plain, target: self, action: #selector(dismissButtonWasPressed))
    vc.navigationItem.leftBarButtonItem = dismissButton

    let nav = UINavigationController(rootViewController: vc)

    self.present(nav, animated: true, completion: nil)
}

Upvotes: 1

Related Questions