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.
2
Answers
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.you should not set a button and its title by using "topItem", instead you should set them by using navigationItem’s rightBarButtonItem.