Search code examples
iosobjective-cnslayoutconstraint

Remove equal width constraint and resize button


I have two buttons in my app that have an equal width constraint.

enter image description here

I need to hide the right side button and resize the left one to fit the entire width of the screen.

I have tried the following (none of which worked):

  1. Hide the right button, remove the equal width constraint programmatically, then resize the left button's frame and, finally, call setNeedsUpdateConstraints. Complete code below:

    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. Update the constraints:

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

How can I hide the right side button and resize the left one to fit the entire width of the screen?


Solution

  • Use a UIStackView with the following setup:

    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
    

    Then you can simply hide one button (leftButton.isHidden = true) and the other one takes the entire width.

    Of course you can do the whole setup in interface builder as well.