【发布时间】:2013-06-13 16:29:31
【问题描述】:
我在 iOS6 中使用自动布局处理 UIScrollView。 我想做的是设置一个滚动视图,其中包含许多子视图(UIViews)。这些子视图是在循环中动态创建的。现在我想添加我的约束,以便它与自动布局一起使用。
在 viewDidLoad 我得到了这个代码:
scrollView.pagingEnabled = YES;
CGRect selfBounds = self.view.bounds;
CGFloat width = CGRectGetWidth(self.view.bounds);
CGFloat height = CGRectGetHeight(self.view.bounds);
NSMutableString *constraintBuilding = [NSMutableString stringWithFormat:@"|"];
NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
for (int i = 0; i < colors.count; i++) {
CGFloat offset = width * i;
UIView* view1 = [[UIView alloc] initWithFrame:CGRectOffset(selfBounds, offset, 0)];
[view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view1 setBackgroundColor:[colors objectAtIndex:i]];
[scrollView addSubview:view1];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view1(height)]|" options:0 metrics:@{@"height":@(height)} views:NSDictionaryOfVariableBindings(view1)]];
[constraintBuilding appendString:[NSString stringWithFormat:@"[view%i(width)]",i+1]];
}
NSMutableArray *views = [[NSMutableArray alloc] init];
for (int j = 0; j < scrollView.subviews.count; j++) {
if (![[scrollView.subviews objectAtIndex:j] isKindOfClass:[UIImageView class]]) {
[views addObject:[scrollView.subviews objectAtIndex:j]];
}
}
[constraintBuilding appendString:@"|"];
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraintBuilding options:0 metrics:@{@"width":@(width*colors.count)} views:NSDictionaryOfVariableBindings(views)]];
循环工作正常,但我会在最后一行出错
[scrollView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:constraintBuilding options:0 metrics:@{@"width":@(width*colors.count)} views:NSDictionaryOfVariableBindings(views)]];
constraintBuilding 说“|[view1(width)][view2(width)][view3(width)]|” 其实我没有 view2 和 view 3 但我不知道如何设置约束?!
这是个例外:
'NSInvalidArgumentException', reason: 'Unable to parse constraint format:
view1 不是视图字典中的键。 |[view1(宽度)][view2(宽度)][view3(宽度)]| ^'
为了测试,我的颜色数组中有 3 个对象,但稍后这个数字会动态变化。
感谢您的帮助!
克里斯
编辑:
还有一件事。 我读了this 文章,效果很好。但不幸的是,它不在一个动态数量的循环中。 :(
与
我阅读了来自苹果的this 文章。但我仍然找不到我的答案。
【问题讨论】:
-
你得到这个工作了吗,我有一个类似的问题,为动态数量的视图创建约束
标签: objective-c ios6 uiview uiscrollview nslayoutconstraint