gpt4 book ai didi

Cocoa 自动布局约束 - 以编程方式填充可变数量的 View

转载 作者:行者123 更新时间:2023-12-03 16:13:11 24 4
gpt4 key购买 nike

我希望能够向 super View 添加新 View ,但使它们彼此之间保持恒定的垂直距离。为此,我尝试以编程方式为每个 View 设置约束,但我不知道如何做到这一点。问题是我事先不知道 View 的数量或相对位置。

有没有一种方法可以以编程方式为每个 View 设置约束,以便无论它们相邻的其他 View 如何,自动布局都会保持 View 之间的恒定间距?

最佳答案

这个简短的代码片段可能就是您正在寻找的:

NSMutableArray* newVerticalConstraints = [NSMutableArray array];
UIView* firstView = nil;
UIView* secondView = nil;
UIView* superview = <Your container view>;
NSArray* subviews = [superview subviews];
if ([subviews count] > 0) {
firstView = [subviews objectAtIndex:0];
// Add first constraint
[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-10-[firstView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstView)]];

for (int i = 1; i < [subviews count]; i++) {
secondView = [subviews objectAtIndex:i];
[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[firstView]-10-[secondView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstView,secondView)]];
firstView = secondView;
}

// Add last constraint
[newVerticalConstraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[firstView]-10-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(firstView)]];

[superview removeConstraints:self.verticalConstraints];
[superview addConstraints:newVerticalConstraints];
// Save all vertical constraints to be able to remove them
self.verticalConstraints = newVerticalConstraints;
}

关于Cocoa 自动布局约束 - 以编程方式填充可变数量的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15844520/

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