我的应用中有两个按钮具有相同的宽度限制。
我需要隐藏右侧按钮并调整左侧按钮的大小以适应屏幕的整个宽度。
我尝试了以下方法(均无效):
隐藏右键,去掉等宽约束 以编程方式,然后调整左侧按钮框架的大小,最后, 调用
setNeedsUpdateConstraints
。完整代码如下:self.btnRight.hidden = YES; [self.view removeConstraint:_btnWidthEqualConstraint]; CGRect buttonFrame = self.btnLeft.frame; buttonFrame.size = CGSizeMake(300, 70); self.btnLeft.frame = buttonFrame; [self.btnLeft setNeedsUpdateConstraints];
更新约束:
UIScreen *screen = [UIScreen mainScreen]; CGRect screenSize = screen.bounds; self.btnRight.hidden = YES; [self.btnRight updateConstraints:^(MASConstraintMaker *make) { make.width.equalTo(@(0)); }]; [self.btnLeft updateConstraints:^(MASConstraintMaker *make) { make.width.equalTo(@(screenSize.size.width-12)); }];
如何隐藏右侧按钮并调整左侧按钮的大小以适应屏幕的整个宽度?
最佳答案
使用具有以下设置的 UIStackView
:
let leftButton = UIButton(type: .system)
let rightButton = UIButton(type: .system)
let stackView = UIStackView(arrangedSubviews: [leftButton, rightButton])
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.distribution = .fillEqually
stackView.spacing = 8 // or whatever spacing you wish to have between the buttons
然后您可以简单地隐藏一个按钮 (leftButton.isHidden = true
),而另一个占据整个宽度。
当然,您也可以在界面生成器中完成整个设置。
关于ios - 删除等宽约束和调整按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624911/