Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a constraint such that a view is as wide as the widest of two other views?

For example, labels A, B and C. Label A should have the width of whichever is wider, B or C.

Visually, something along the lines of

@"H:[viewA(==MAX(viewB,viewC))]"
like image 287
Ben Packard Avatar asked Nov 13 '22 01:11

Ben Packard


1 Answers

If you want to ensure that viewA is simultaneously at least as wide as both viewB and viewC, then use two separate VFL statements, @"H:[viewA(>=viewB)]" and @"H:[viewA(>=viewC)]".

If you also want to ensure that A will not be wider than the maximum width of viewB and/or viewC, you would define an optional constraint (i.e. lower priority than UILayoutPriorityRequired) for the width of viewA to be equal to one of them, e.g.:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:viewA
                                                              attribute:NSLayoutAttributeWidth
                                                              relatedBy:NSLayoutRelationEqual
                                                                 toItem:viewB
                                                              attribute:NSLayoutAttributeWidth
                                                             multiplier:1.0
                                                               constant:0.0];
constraint.priority = UILayoutPriorityDefaultLow;
[viewA.superview addConstraint:constraint];

According to the documentation for priority:

If a constraint 'a == b' is optional, the constraint-based layout system will attempt to minimize 'abs(a-b)'.

Thus, if viewB is larger than viewC, this optional constraint will be satisfied and viewA will be as wide as viewB. If viewB is smaller than viewC, the constraint system will satisfy the required @"H:[viewA(>=viewC)]" constraint, but then will also minimize the abs(a-b), effectively making viewA the same width as viewC.

In practice, you probably don't need this optional viewA==viewB constraint, but if you want to ensure that viewA won't be wider than both viewB and viewC, then add this final optional constraint.

like image 134
Rob Avatar answered Nov 15 '22 05:11

Rob