我正在尝试在将自动调整大小的超级视图中添加 3 个按钮,以使它们具有相同的宽度。我通过像这样添加一个又一个约束来做到这一点:
for (UIButton* btn in _buttonsArray) {
btn.translatesAutoresizingMaskIntoConstraints = NO;
[self.buttonsView addSubview:btn];
[self.buttonsView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-(0)-[btn(40)]"
options:0
metrics:nil
views:NSDictionaryOfVariableBindings(_buttonsView, btn)]];
UIButton *prevBtn;
int prevIndex = [_buttonsArray indexOfObject:btn]-1;
int nextIndex = [_buttonsArray indexOfObject:btn]+1;
if ( prevIndex >= 0) {
//there is a prev button
prevBtn = _buttonsArray[prevIndex];
} else {
//first button
NSDictionary* views = NSDictionaryOfVariableBindings(_buttonsView, btn);
[self.buttonsView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(15)-[btn]"
options:0
metrics:nil
views:views]];
}
if (prevBtn) {
NSDictionary* views = NSDictionaryOfVariableBindings(prevBtn, btn);
[self.buttonsView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[prevBtn]-(5)-[btn]"
options:0
metrics:nil
views:views]];
}
if (nextIndex >= [_buttonsArray count]){
//lastBtn
NSDictionary* views = NSDictionaryOfVariableBindings(btn, _buttonsView);
[self.buttonsView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[btn]-(15)-|"
options:0
metrics:nil
views:views]];
}
}
打印buttonsView的约束给了我这个:
"<NSLayoutConstraint:0x845b760 V:[UIView:0x845b700(51)]>",
"<NSLayoutConstraint:0x8465310 V:|-(0)-[UIButton:0x845b7b0] (Names: '|':UIView:0x845b700 )>",
"<NSLayoutConstraint:0x8465110 V:[UIButton:0x845b7b0(40)]>",
"<NSLayoutConstraint:0x84655a0 H:|-(15)-[UIButton:0x845b7b0] (Names: '|':UIView:0x845b700 )>",
"<NSLayoutConstraint:0x84656f0 V:|-(0)-[UIButton:0x8464e00] (Names: '|':UIView:0x845b700 )>",
"<NSLayoutConstraint:0x8465750 V:[UIButton:0x8464e00(40)]>",
"<NSLayoutConstraint:0x84658a0 H:[UIButton:0x845b7b0]-(5)-[UIButton:0x8464e00]>",
"<NSLayoutConstraint:0x84659b0 V:|-(0)-[UIButton:0x8464ec0] (Names: '|':UIView:0x845b700 )>",
"<NSLayoutConstraint:0x8465a10 V:[UIButton:0x8464ec0(40)]>",
"<NSLayoutConstraint:0x8465b80 H:[UIButton:0x8464e00]-(5)-[UIButton:0x8464ec0]>",
"<NSLayoutConstraint:0x8465c90 H:[UIButton:0x8464ec0]-(15)-| (Names: '|':UIView:0x845b700 )>"
它在理论上看起来不错,但只出现了最后一个按钮,而且它比它应该的要宽得多。知道有什么问题吗?非常感谢!