gpt4 book ai didi

ios - constraintsWithVisualFormat 可以用于未知数量的 View 吗?

转载 作者:行者123 更新时间:2023-11-28 22:00:27 24 4
gpt4 key购买 nike

假设我有一个动态创建的 UIView 数组,并且我将它们添加到同一个父 View ,我可以使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com