Search code examples
iosobjective-ciphoneautolayoutnslayoutconstraint

How to set constraints programmatically for a varying number of UIView


I'm new to auto layout constraints. In my application there are 3 buttons in one line. Now I want to set the constraints programatically as shown in the image below:

Image flow

If there is one, then the button show in center horizontally. If two buttons are enable, then second line shown in same image as three image.


Solution

  • My approach is to setting all buttons centerX to superview's centerX at the beginning.

    IBOutletCollection(UIButton) NSArray *allButtons;
    //3 buttons' references
    IBOutletCollection(NSLayoutConstraint) NSArray *allButtonCenterConstraints;
    //buttons' centerX constraints' references
    

    and then if in viewDidAppear:

    int t = arc4random() %3;// one of the 3 cases you will need
    
    
        if (t == 0) {//if you want all 3 buttons appears
            //all buttons shown
            NSLayoutConstraint *c1 = allButtonCenterConstraints[0];//first button's centerX reference.
            NSLayoutConstraint *c2 = allButtonCenterConstraints[2];//third button's centerX reference.
    
            c1.constant = -self.view.frame.size.width*0.25;//push left
            c2.constant = +self.view.frame.size.width*0.25;//push right
        }
        else if (t == 1)
        {
            //two buttons shown;
            [allButtons[0] setHidden:YES];// close the one you dont need
            NSLayoutConstraint *c1 = allButtonCenterConstraints[1];
            NSLayoutConstraint *c2 = allButtonCenterConstraints[2];
    
            c1.constant = -self.view.frame.size.width*0.125;
            c2.constant = +self.view.frame.size.width*0.125;
    
        }
        else
        {
            //close 2 buttons
            [allButtons[0] setHidden:YES];
            [allButtons[1] setHidden:YES];
        }
        [self.view layoutIfNeeded];
    

    if you need something depends on the width of buttons, you can set the constants according to the width of buttons.