4
我希望能夠將新的視圖添加到超級視圖,但它們保持彼此之間的恆定垂直距離。爲此,我嘗試以編程方式爲每個視圖設置約束,但我無法弄清楚如何去做。問題是我不知道視圖的數量或相對位置。可可自動佈局約束 - 可變數量的視圖的編程填充
有沒有一種方法可以爲每個視圖編程設置一個約束,以便不管其他視圖是否與其相鄰,自動佈局會保持視圖之間的恆定間距?
我希望能夠將新的視圖添加到超級視圖,但它們保持彼此之間的恆定垂直距離。爲此,我嘗試以編程方式爲每個視圖設置約束,但我無法弄清楚如何去做。問題是我不知道視圖的數量或相對位置。可可自動佈局約束 - 可變數量的視圖的編程填充
有沒有一種方法可以爲每個視圖編程設置一個約束,以便不管其他視圖是否與其相鄰,自動佈局會保持視圖之間的恆定間距?
可能這短短的代碼片段是你在找什麼:
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;
}