ios - 删除等宽约束和调整按钮

标签 ios objective-c nslayoutconstraint

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

enter image description here

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

我尝试了以下方法(均无效):

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

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

关于ios - 删除等宽约束和调整按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52624911/

相关文章:

ios - 在第二个动画之前查看跳跃

ios - 仅在切换 View Controller 时出现 NSLayoutConstraint 错误

ios - 更改照片编辑扩展的标题

ios - 使用 CameraManager 和 Swift 将捕获的视频保存到 iOS 库

objective-c - 使用 objective c for mac 截屏

iphone - 基于网络连接发送电子邮件或短信(慢/快)

ios - 使用自动布局的 UIScrollView 中的 UITableView

c# - 在所有 UIButton 上设置自定义字体

ios - MPMediaPickerController 空白屏幕,各种错误,正确的 Info.plist 文件(iOS 13.1.3)

objective-c - 如何构建和归档 iOS 应用程序?