确保UIScrollView中的子视图使用autolayout一个接一个地水平堆叠的最佳方法是什么?子视图的数量会有所不同,所以我不能使用IB,但必须以编程方式进行。我理解布局约束如何工作,但解决它的最佳方法是什么?每次更新子视图的数量时,循环所有子视图并更新每个视图的约束?如果是这样,是否有一个简单的解决方案来引用布局约束中的前一个兄弟,或者我是否必须保留对前一个兄弟的引用?
答案 0 :(得分:0)
我为应用编写了以下方法。可能不是最漂亮,但它完成了工作。它将视图作为一个数组来解决引用前一个视图的问题。它还使用透明的间隔视图来均匀地隔开它们,但您可以轻松地将它们取出来。
+(void)spaceViews:(NSArray*)views evenlyInContainer:(UIView*)container {
UIView* lastSpacer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
lastSpacer.translatesAutoresizingMaskIntoConstraints = NO;
[lastSpacer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastSpacer(10)]" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(lastSpacer)]];
[container addSubview:lastSpacer];
[container addConstraint:[NSLayoutConstraint constraintWithItem:container attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:lastSpacer attribute:NSLayoutAttributeLeading multiplier:1.f constant:0]];
for (int i = 0; i < [views count]; i++) {
[container addSubview:views[i]];
[container addConstraint:[NSLayoutConstraint constraintWithItem:lastSpacer attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:views[i] attribute:NSLayoutAttributeLeading multiplier:1.f constant:0]];
UIView* spacerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
[spacerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[spacerView(10)]" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(spacerView)]];
spacerView.translatesAutoresizingMaskIntoConstraints = NO;
[spacerView setBackgroundColor:[UIColor blueColor]];
[container addSubview:spacerView];
[container addConstraint:[NSLayoutConstraint constraintWithItem:spacerView attribute:NSLayoutAttributeLeading relatedBy:NSLayoutRelationEqual toItem:views[i] attribute:NSLayoutAttributeTrailing multiplier:1.f constant:0]];
[container addConstraint:[NSLayoutConstraint constraintWithItem:spacerView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:container attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0]];
[container addConstraint:[NSLayoutConstraint constraintWithItem:views[i] attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:container attribute:NSLayoutAttributeCenterY multiplier:1.f constant:0]];
if (lastSpacer) {
[container addConstraint:[NSLayoutConstraint constraintWithItem:spacerView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:lastSpacer attribute:NSLayoutAttributeWidth multiplier:1.f constant:0]];
}
lastSpacer = spacerView;
}
[container addConstraint:[NSLayoutConstraint constraintWithItem:lastSpacer attribute:NSLayoutAttributeTrailing relatedBy:NSLayoutRelationEqual toItem:container attribute:NSLayoutAttributeTrailing multiplier:1.f constant:0]];
}