Ios 是否可以将constraintsWithVisualFormat用于数量未知的视图?
假设我有一个动态创建的UIView数组,并将它们添加到同一父视图中,我可以使用constraintsWithVisualFormat来设置约束,以便它们垂直堆叠吗?constraintsWithVisualFormat中要求的ascii艺术似乎不允许这样做 如果没有,最好的做法是什么 谢谢 非常简单:Ios 是否可以将constraintsWithVisualFormat用于数量未知的视图?,ios,ios7,autolayout,nslayoutconstraint,Ios,Ios7,Autolayout,Nslayoutconstraint,假设我有一个动态创建的UIView数组,并将它们添加到同一父视图中,我可以使用constraintsWithVisualFormat来设置约束,以便它们垂直堆叠吗?constraintsWithVisualFormat中要求的ascii艺术似乎不允许这样做 如果没有,最好的做法是什么 谢谢 非常简单: UIView *view1 = [UIView new]; [view1 setTranslatesAutoresizingMaskIntoConstraints:NO]; [view1 setB
UIView *view1 = [UIView new];
[view1 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view1 setBackgroundColor:[UIColor redColor]];
UIView *view2 = [UIView new];
[view2 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view2 setBackgroundColor:[UIColor blueColor]];
UIView *view3 = [UIView new];
[view3 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view3 setBackgroundColor:[UIColor yellowColor]];
UIView *view4 = [UIView new];
[view4 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view4 setBackgroundColor:[UIColor blackColor]];
UIView *view5 = [UIView new];
[view5 setTranslatesAutoresizingMaskIntoConstraints:NO];
[view5 setBackgroundColor:[UIColor greenColor]];
NSArray *arrayOfViews = @[view1, view2, view3, view4, view5];
UIView *superview = self.view; //I tested in ViewController
[arrayOfViews enumerateObjectsUsingBlock:^(UIView *currentView, NSUInteger idx, BOOL *stop) {
[superview addSubview:currentView];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[view]|" options:0 metrics:nil
views:@{@"view" : currentView}]];
if (idx == 0)//If First element
{
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]" options:0 metrics:nil
views:@{@"view" : currentView}]];
}
else if (idx != [arrayOfViews count] - 1)
{ //Not last element
UIView *brotherView = arrayOfViews[idx - 1];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[brotherView][currentView(brotherView)]" options:0 metrics:nil
views:@{@"brotherView" : brotherView, @"currentView" : currentView}]];
}
else //Last element
{
UIView *brotherView = arrayOfViews[idx - 1];
[superview addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[brotherView][currentView(brotherView)]|" options:0 metrics:nil
views:@{@"brotherView" : brotherView, @"currentView" : currentView}]];
}
}];
这看起来很棒,谢谢。实际上,我做了一些非常类似的事情,但我没有索引数组,而是创建了一个指向最近视图的指针,以便可以在该视图的基础上添加一个约束。