gpt4 book ai didi

ios - 使用自动布局 VFL 垂直堆叠一组按钮

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:15:03 32 4
gpt4 key购买 nike

我正在学习自动布局,我想设置一组垂直堆叠且间隔均匀的按钮。我还希望按钮固定在 View 底部。使用 VFL 设置这些约束的好方法是什么?按钮列表将作为 UIButton 数组传入。

NSArray *buttons = [button1, button2, button3, button4, ...]
NSMutableArray *allConstraints = [NSMutableArray array]
UIButton *previousButton;

for (UIButton button in buttons) {
// Buttons take up full width
NSArray *constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"H:|[button]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(button);];
[allConstraints addObjectsFromArray:constraints];

constraints = [NSLayoutConstraint
constraintsWithVisualFormat:@"V:|[button]|"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(button);];
[allConstraints addObjectsFromArray:constraints];

if (!previousButton) {
NSDictionary *metrics = @{@"padding" : @(10)};

// Make buttons height
constraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:[-(padding)-previousButton(==button)]"
options:0
metrics:metrics
views:NSDictionaryOfVariableBindings(previousButton, button)];
[allConstraints addObjectsFromArray:constraints];
}
previousButton = button;
}

[self.view addConstraints:allConstraints]

这没有达到我的需要,因为按钮没有固定到 View 的底部。

最佳答案

我会以不同的方式来做。我不会在循环中构建约束,而是在循环中构建格式字符串。

-(void)addButtonsWithConstraints:(NSArray *) buttons {
NSMutableDictionary *views = [NSMutableDictionary new];
for (int i = 0; i<buttons.count; i++) {
[buttons[i] setTranslatesAutoresizingMaskIntoConstraints: NO];
[self.view addSubview:buttons[i]];
[views setObject:buttons[i] forKey:[NSString stringWithFormat:@"button%d",i]];
}

NSMutableString *formatString = [@"V:" mutableCopy];
for (int i = 0; i<buttons.count-1; i++) {
[formatString appendFormat:@"[button%d]-10-", i];
}
[formatString appendFormat:@"[button%lu]|", buttons.count - 1]; // pins the last button to the bottom of the view
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:formatString options:NSLayoutFormatAlignAllLeft | NSLayoutFormatAlignAllRight metrics:nil views:views]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[button0]|" options:0 metrics:nil views:views]];
}

最后一行将 button0 设置为 View 的全宽,上一行中的格式选项使所有按钮的左右边缘对齐。

关于ios - 使用自动布局 VFL 垂直堆叠一组按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28769481/

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