When programmatically creating layouts, I follow Apple's advice: override -updateConstraints, add custom constraints, and call -setNeedsUpdateConstraints once subviews have been added to the view. My typical setup looks like this:
- (void)setupViews
{
//Style View
//Add gesture recognizers
//Add Subviews
[self setNeedsUpdateConstraints];
}
- (void)updateConstraints
{
//Add custom constraints
[super updateConstraints];
}
The problem
There are occasions when -updateConstraints gets fired multiple times (for example, when a view's controller is presented or pushed w/ animation). The problem here is that each constraint added gets re-added. This becomes a serious problem when trying to on-demand change the constant of an added constraint, since there are two of the original constraint that subsequently conflict with each other. I imagine that even when you aren't manipulating the constraints after creating them, having double what you doesn't seem good.
Potential solutions
1 - Remove all constraints effecting the view before applying them in -updateConstraints:
- (void)updateConstraints
{
//Remove all constraints affecting view & subviews
//Add custom constraints
[super updateConstraints];
}
2 - Set a layout flag & check against it before adding custom constraints:
- (void)updateConstraints
{
if (self.didAddConstraints) {
[super updateConstraints];
return;
}
//Add custom constraints
self.didAddConstraints = YES;
[super updateConstraints];
}
3 - Don't worry about doubling up on constraints, and whenever changing a constant is needed, only remove that constraint before re-adding.
3 - Something awesome that I haven't thought of.
What's the best practice here?
setNeedsUpdateConstraints
andupdateConstraints
. You mentioned updating constants - in that case, you only needsetNeedsLayout
. My understanding is thatupdateConstraints
is intended for wholesale changes to the layout - if you are changing the structure of the view, not just parameters. It is intended to have one place / time to dramatically change constraints, to avoid churn of updating after small state changes. That said, in the state property setting code, you also update the specific corresponding constraint, and call setNeedsDisplay.