0

Just like the title says, I'm trying to replace the rightBarButtonItems for a view controller when pushing a new controller using the navigation view controller. Weirdly, sometimes this works just fine and sometimes not at all.

Swift 4.2, XCode 10.3

The code

Push the VC:

 DispatchQueue.main.async {
                guard let vc = UIStoryboard(name: "ExampleStoryboard", bundle: Bundle.main).instantiateViewController(withIdentifier: "ExampleViewController") as? ExampleViewController else {
                    return
                }

                vc.data = Data(JSON: newDataJson)
                vc.delegate = self
                vc.images = self.images
                self.navigationController?.pushViewController(vc, animated: true)
            }

Set the barButtonItems:

override func viewDidLoad() {
        super.viewDidLoad()
//        [Some other stuff here...]
        let btn = UIButton(type: .custom)
        btn.setImage(#imageLiteral(resourceName: "icon-image"), for: .normal)
        btn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
        btn.imageEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        btn.addTarget(self, action: #selector(performAction), for: .touchUpInside)
        self.navigationItem.rightBarButtonItems = [UIBarButtonItem(customView: btn)]
        }
    }

I've read as many questions regarding this topic on SO and various other websites as well as the developer documentation for navigationItem and UINavigationViewController and anything else I could think of. So far I haven't been able to find anything to solve this.

I've tried putting the bar button code in viewDidLoad, viewWillAppear, viewDidAppear, didMoveTo(parent:)... I also tried putting it in a button in the pushed VC and no dice. But this has worked in this exact situation before on previous builds.

The rootVC has rightBarButtonItems which would be overridden by this. I tried setting the parent items as well.

I've also tried this with/without DispatchQueue.main.

I was able to confirm through debugging that the navigationItem does not match the root navigationItem when this is attempting to be set.

Any further info about what might be happening or how to work around/fix this would be very appreciated.

2
  • What do you mean sometimes not at all.. Is the button shown or not? The code looks correct. Check if you have rightBarButtonItems in other places. Commented Sep 9, 2019 at 18:50
  • Sometimes it's displayed, sometimes it is not. We ended up figuring out sort of what was going on. Commented Sep 10, 2019 at 5:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.