简体   繁体   English

如何以编程方式为不同数量的UIView设置约束

[英]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. 在我的应用程序中,一行中有3个按钮。 Now I want to set the constraints programatically as shown in the image below: 现在我想以编程方式设置约束,如下图所示:

图像流

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. 如果启用了两个按钮,则第二行显示在与三个图像相同的图像中。

My approach is to setting all buttons centerX to superview's centerX at the beginning. 我的方法是将所有按钮centerX设置为centerXcenterX

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

and then if in viewDidAppear: 然后如果在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. 如果你需要的东西取决于按钮的宽度,你可以根据按钮的宽度设置常量。

Make constraint outlet after that you set constraint pragmatically 在您以实际方式设置约束之后创建约束出口

like as : 像:

@IBOutlet var mainViewWidthConstant: NSLayoutConstraint! @IBOutlet var mainViewWidthConstant:NSLayoutConstraint!

    if (self.view.frame.size.width == 320){

        mainViewWidthConstant.constant = 320

    }
    else if (self.view.frame.size.width == 375)
    {
        mainViewWidthConstant.constant = 375

    }
    else{
        mainViewWidthConstant.constant = 414

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM