Cocoa autolayout constraint - programmatic padding

2020-07-18 02:43发布

问题:

I want to be able to add new views to a superview but so that they keep a constant vertical distance between each other. For that I tried to programmatically set up a constraint for each view but I could not figure out how to do it. The problem is I do not know beforehand the number or the relative position of the views.

Is there a way to programmaically set up a constraint for each view so that regardless of whatever other views they neighbor, autolayout will keep the constant spacing between the views?

回答1:

Possible this short code snippet is what you are looking for:

NSMutableArray* newVerticalConstraints = [NSMutableArray array];
UIView* firstView = nil;
UIView* secondView = nil;
UIView* superview = <Your container view>;
NSArray* subviews = [superview subviews];
if ([subviews count] > 0) {
    firstView = [subviews objectAtIndex:0];
    // Add first constraint
    [newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[firstView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstView)]];

    for (int i = 1; i < [subviews count]; i++) {
        secondView = [subviews objectAtIndex:i];
        [newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[firstView]-10-[secondView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstView,secondView)]];
        firstView = secondView;
    }

    // Add last constraint
    [newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[firstView]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstView)]];

    [superview removeConstraints:self.verticalConstraints];
    [superview addConstraints:newVerticalConstraints];
    // Save all vertical constraints to be able to remove them
    self.verticalConstraints = newVerticalConstraints;
}