0

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

2 Answers2

1

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)
Sajjad Sarkoobi
  • 827
  • 8
  • 18
0

Issue was caused by creating bar button not from child VC, but coordinator.

Bar buttons are stored in navigationItem property of UIViewController.