-1

In my app, the first ViewController appears with right navigation bar items. I want to show different bar items on right side in child VC which is appeared by pushing. The items in the first VC shows fine, but the second doesn't. The bar button shows for a second when the VC disappeared.

// The things the first VC did 
        navigationItem.setHidesBackButton(true, animated: true)
        navigationController?.navigationBar.tintColor = .gray600

        let stackView = UIStackView()
        stackView.addArrangedSubviews(views: [registerButton, notificationButton])
        stackView.spacing = 16

        let rightBarButton = UIBarButtonItem(customView: stackView)
        navigationController?.navigationBar.topItem?.rightBarButtonItem = rightBarButton
// The things the second did 
        navigationController?.navigationBar.tintColor = .gray600
        
        navigationController?.navigationBar.topItem?.backButtonTitle = ""
        navigationController?.navigationBar.backIndicatorImage = .back
        navigationController?.navigationBar.backIndicatorTransitionMaskImage = .back
        
        let rightBarButton = UIBarButtonItem(customView: editButton)
        navigationController?.navigationBar.topItem?.rightBarButtonItem = rightBarButton

They did almost same things but the second doesn't work.

Here is the gif file i recorded. You can see Edit button for a second when the second VC disappeared. I tried to find the clues but i couldn't. Please check it and give me any comments. Thank you.

6sbdoa

doori
  • 85
  • 1
  • 6

2 Answers2

0

Delete the phrase navigationController?.navigationBar.topItem everywhere it appears, and never use it again, ever. It will totally break the navigation controller — as you yourself have demonstrated.

The only navigation item a view controller can talk to is its own navigationItem property. Thus the first vc is much more correct than the second vc, and so it works much better than the second vc.

matt
  • 515,959
  • 87
  • 875
  • 1,141
0

you should not set a button and its title by using "topItem", instead you should set them by using navigationItem's rightBarButtonItem.

let rightBarButton = UIBarButtonItem(customView: editButton)
navigationItem.rightBarButtonItem = rightBarButton

let backButton = UIBarButtonItem(...)
navigationItem.leftBarButtonItem = backButton
musakokcen
  • 359
  • 2
  • 12
  • Isn't that exactly what I already said? – matt Sep 05 '22 at 21:08
  • isn't this explanation more helpful to the question owner? s/he shared the code, I showed the proper implementation. In the shared gif, the back button looks good but it should also be handled as seen above. – musakokcen Sep 06 '22 at 06:45