删除等宽约束并调整按钮大小

时间:2018-10-03 10:22:54

标签: 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));
    }];
    

如何隐藏右侧按钮并调整左侧按钮的大小以适合屏幕的整个宽度?

3 个答案:

答案 0 :(得分:2)

通过以下设置使用def ya_done(): ##### WHY CAN'T I FIND THE POSITION? :( ##### print(Global.prv_word) print(Global.cur_word) print(Global.nxt_word) ##### PRINT POSITION OF ADJECTIVE DESCRIBING DOG IN DOG LIST ##### exec(f"""if Global.prv_word in Dog.{Global.cur_word}[0]: print(Dog.{Global.cur_word}.index('{Global.prv_word}'))""")

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

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

答案 1 :(得分:1)

  1. 您可以在每个按钮上添加宽度限制,并设置宽度限制> = 1
  2. 之后,将所有“相等约束” 优先级设置为1,并将宽度约束优先级设置为(例如)1000
  3. 根据您的条件在.m文件中设置该值之后,您可以基于优先级设置另一个宽度约束:

self.yourButtonWidthConstraint.constant = yourWidth;

答案 2 :(得分:0)

请使用@property CGFloat constant更新约束。

隐藏右键:

_btnWidthEqualConstraint.constant = UIScreen.mainScreen.bounds.size.width - _btnLeftLeading.constant - _btnRightTrailing.constant;
_spacing.constant = 0; 

显示右键:

_btnWidthEqualConstraint.constant = 0;
_spacingBetweenBtns.constant = 8; //Specify the spacing between two buttons

请确保实施_btnWidthEqualConstraint like this

相关问题