Search code examples
swiftuinavigationcontrolleruibarbuttonitemswift5

Adding a UIBarButtonItem programmatically


I'm trying to add a UIBarButtonItem programmatically.

let navigation = UINavigationController()
let rightBarButton = UIBarButtonItem(title: "LogIn", style: .plain, target: self, action: #selector(logInPressed))
navigation.navigationItem.rightBarButtonItem = rightBarButton

And also made a selector function for testing.

@objc func logInPressed() {
   print("go to login")
}

Unfortunately that does not work - bar button is not visible on navigation bar in simulator.

Checked with a breakpoint, rightBarButtonItem exists.

Probably issue can be caused by creating bar button from app coordinator, not from child VC.

Could please anyone help to troubleshoot this issue? Simulator screenshot


Solution

  • you are adding UIBarButtonItem to a new instance of NavigationController. so it will not appear there.

    so in your view controller which you want to handle right navigation bar , under one of these methods: override func viewDidLoad() or override func viewWillAppear

    add:

    let rightBarButton = UIBarButtonItem(title: "LogIn", style: .plain, target: self, action: #selector(logInPressed))
    
    self.navigationController?.navigationItem.setRightBarButton(rightBarButton, animated: true)