0

I am adding a custom subview into the navigation bar from a view controller like so (width is derived at layout from the button's contentMode = .scaleAspectFit):

// navigationBar is just sugar for navigationController.navigationBar
navigationBar?.addSubview(button)
button.centerYAnchor.constraint(equalTo: navigationBar!.centerYAnchor).isActive = true
button.leftAnchor.constraint(equalTo: navigationBar!.leftAnchor, constant: navigationBar!.bounds.size.width / 18).isActive = true
button.heightAnchor.constraint(equalTo: navigationBar!.heightAnchor, multiplier: 0.5).isActive = true

In my viewDidDisappear I attempted to do a button.removeFromSuperview() but ended up with a crash:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot modify constraints for UINavigationBar managed by a controller'

which I have trouble to understand. I have tried tagging the button and removing it from a UINavigationControllerDelegate without success.

Is there something I am doing fundamentally wrong?

Thanks in advance.

Herakleis
  • 513
  • 5
  • 21
  • Possible duplicate of [Adding autolayout constraints to navigation controller programatically](https://stackoverflow.com/questions/28708074/adding-autolayout-constraints-to-navigation-controller-programatically) – DonMag Jul 13 '17 at 16:36

2 Answers2

3

First make all constraints inactive and remove from superview,

override func viewDidDisappear(_ animated: Bool) {
    button.constraints.forEach { $0.isActive = false }
    button.removeFromSuperview()
}
Elijah
  • 8,381
  • 2
  • 55
  • 49
3

At my case removing constraints worked like a charm. Note: I used from snapKit. And before removing navigationBar's subview I removed all constraints from this subview.

for instance:

someSubview.snp.removeConstraints()
someSubview.removeFromSuperview()

That is all.