How can I pin more than two UIViews with Widths Equally using NSLayoutConstraints?
Right now, I'm using the following code and I can't pin more than two UIViews:
for (int i = 0; i < column.count; i++) {
NSString *horizontalFormat = @"H:|[view1][view2(==view1)]|";
NSDictionary *views;
if (i < column.count - 1) {
views = @{
@"view1": column[i],
@"view2": column[i + 1]
};
}else{
views = @{
@"view1": column[i - 1],
@"view2": column[i]
};
}
NSArray * horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:horizontalFormat
options:NSLayoutFormatAlignAllTop | NSLayoutFormatAlignAllBottom
metrics:nil
views:views];
[self.contentView addConstraints:horizontalConstraints];
}
Any ideas?
Here's an example. All views are generated in the code, so just copy this code right into a UIViewController (e.g. into its
viewDidLoad
) and run it:Each NSLayoutConstraint can only relate two views, but nothing is stopping you from adding additional constraints. E.g:
If you add these two constraints, the "columns" at i-1, i, and i+1 will now all have equal widths.