假设我有一个动态创建的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}]];
}
}];
关于ios - 可以将constraintsWithVisualFormat与未知数量的 View 一起使用吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25297515/