constraintsWithVisualFormat可以用于未知数量的视图吗?



假设我有一个动态创建的uiview数组,我将它们添加到相同的父视图,我可以使用constraintsWithVisualFormat来设置设置约束,使它们垂直堆叠?在constraintsWithVisualFormat中所需的ascii艺术似乎不允许。

如果没有,最好的做法是什么?

谢谢!

很简单:

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}]];
    }
}];