4

我希望能够将新视图添加到超级视图,但它们之间的垂直距离保持不变。为此,我尝试以编程方式为每个视图设置一个约束,但我不知道该怎么做。问题是我事先不知道视图的数量或相对位置。

有没有办法以编程方式为每个视图设置约束,以便无论它们相邻的其他视图如何,自动布局都会保持视图之间的恒定间距?

4

1 回答 1

7

这个简短的代码片段可能是您正在寻找的:

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;
}
于 2013-04-07T18:21:23.010 回答