Home > Back-end >  RightBarButton doesn't appear but it appears when the ViewController disappear for a second
RightBarButton doesn't appear but it appears when the ViewController disappear for a second

Time:09-06

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

CodePudding user response:

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.

CodePudding user response:

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
  • Related