constraintsWithVisualFormat可以与未知数量的视图一起使用吗?

时间:2014-08-13 22:53:19

标签: ios ios7 autolayout nslayoutconstraint

假设我有一个动态创建的UIViews数组,并且我将它们添加到同一个父视图中,我可以使用constraintsWithVisualFormat设置集合约束,使它们垂直堆叠吗? constraintsWithVisualFormat中所需的ascii艺术似乎不允许这样做。

如果没有,那么最佳做法是什么?

谢谢!

1 个答案:

答案 0 :(得分:2)

非常简单:

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