可可自动布局约束 - 的意见可变数量的纲领性填充 [英] Cocoa autolayout constraint - programmatic padding of variable number of views
问题描述
欲能够新视图添加至上海华但使得它们保持相互之间的恒定的垂直距离。对于我试图以编程方式设置为每个视图约束,但我无法弄清楚如何做到这一点。问题是我不知道事先的数量或观点的相对位置。
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.
有没有programmaically设置为每个视图约束这样不管什么其他看法,他们的邻居,自动布局将保持视图之间均匀间隔的方式?
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?
推荐答案
可能这短短code片段是你在找什么:
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;
}
这篇关于可可自动布局约束 - 的意见可变数量的纲领性填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!