Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which operations will invalidate constraints?

Tags:

ios

autolayout

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.

like image 522
an0 Avatar asked Dec 13 '13 01:12

an0


2 Answers

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.

like image 99
an0 Avatar answered Oct 24 '22 13:10

an0


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.

like image 29
Max MacLeod Avatar answered Oct 24 '22 12:10

Max MacLeod