Reputation: 533
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.
Upvotes: 1
Views: 2287
Reputation: 81
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.
Upvotes: 4
Reputation: 333
First make all constraints inactive and remove from superview,
override func viewDidDisappear(_ animated: Bool) {
button.constraints.forEach { $0.isActive = false }
button.removeFromSuperview()
}
Upvotes: 4