删除等宽约束和调整按钮

Remove equal width constraint and resize button

我的应用程序中有两个具有相等宽度限制的按钮。

我需要隐藏右侧按钮并调整左侧按钮的大小以适合整个屏幕宽度。

我尝试了以下方法(none 有效):

  1. 隐藏右键,去掉等宽约束 以编程方式,然后调整左侧按钮框架的大小,最后, 呼叫 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]; 
    
  2. 更新约束:

    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),另一个占据整个宽度。

当然您也可以在界面生成器中完成整个设置。

  1. 您可以在每个按钮上添加宽度限制并设置宽度限制 >= 1
  2. 之后将所有 "equal constraints" priority 设置为 1 并将宽度约束 priority 设置为(例如)1000
  3. 之后,根据您的情况在 .m 文件中,您可以根据优先级设置另一个宽度限制:

self.yourButtonWidthConstraint.constant = 你的宽度;