UIView
's updateConstraints
method has a note:
You must not invalidate any constraints as part of your constraint update phase. You also must not invoke a layout or drawing phase as part of constraint updating.
It is not clear to me what would invalidate constraints.
Through some experiments, I found that simply adding, removing or editing constraints will not automatically have setNeedsUpdateConstraints
get called. In fact, I can't find any way to get setNeedsUpdateConstraints
called automatically by the system. Together with my observation that updateConstraints
will not be called without setNeedsUpdateConstraints
or invalidateIntrinsicContentSize
being called first, I think the only meaningful way to invalidate any constraints is by calling setNeedsUpdateConstraints
or invalidateIntrinsicContentSize
myself. Thus the implication of the note in the question post is:
You must not call [self setNeedsUpdateConstraints] or [self invalidateIntrinsicContentSize] in updateConstraints.
Excellent question!
Richard Warren covers this in his blog tutorial UNDERSTANDING AUTO LAYOUT:
If we want to invalidate a view’s constraints, we should remove the old constraints, then call setNeedsUpdateConstraints. Our custom updateConstraints or updateViewConstraints methods can then provide the new constraints.
Constraints should not be invalided in the updateConstraints
method. This is explicitly stated in the UIView Class Reference:
Custom views that set up constraints themselves should do so by overriding this method. When your custom view notes that a change has been made to the view that invalidates one of its constraints, it should immediately remove that constraint, and then call setNeedsUpdateConstraints to note that constraints need to be updated. Before layout is performed, your implementation of updateConstraints will be invoked, allowing you to verify that all necessary constraints for your content are in place at a time when your custom view’s properties are not changing.
You may not invalidate any constraints as part of your constraint update phase. You also may not invoke a layout or drawing phase as part of constraint updating.
This is different to the view controller equivalent updateViewConstraints
. There is no similar stipulation not to invalidate constraints in that method. Certainly, Erica Sadun's book shows sample code that does just that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With