Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/114.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何以编程方式为不同数量的UIView设置约束_Ios_Objective C_Iphone_Autolayout_Nslayoutconstraint - Fatal编程技术网

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

Ios 如何以编程方式为不同数量的UIView设置约束,ios,objective-c,iphone,autolayout,nslayoutconstraint,Ios,Objective C,Iphone,Autolayout,Nslayoutconstraint,我不熟悉自动布局约束。在我的应用程序中,一行有3个按钮。现在我想以编程方式设置约束,如下图所示: 如果有,则按钮水平显示在中间。 如果两个按钮处于启用状态,则第二行显示在与三个图像相同的图像中。设置约束出口,然后实际设置约束 例如: @IBOutlet var mainViewWidthConstant:NSLayoutConstraint if (self.view.frame.size.width == 320){ mainViewWidthConstant.co

我不熟悉自动布局约束。在我的应用程序中,一行有3个按钮。现在我想以编程方式设置约束,如下图所示:

如果有,则按钮水平显示在中间。
如果两个按钮处于启用状态,则第二行显示在与三个图像相同的图像中。

设置约束出口,然后实际设置约束

例如:

@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

    }

我的方法是在开始时将所有按钮
centerX
设置为superview的
centerX

IBOutletCollection(UIButton) NSArray *allButtons;
//3 buttons' references
IBOutletCollection(NSLayoutConstraint) NSArray *allButtonCenterConstraints;
//buttons' centerX constraints' references
然后如果在
视图中出现:

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

如果您需要的东西取决于按钮的宽度,您可以根据按钮的宽度设置常量。

堆栈视图是这样做的最佳方式,但它仅在ios 8UIStackView从iOS9开始可用后才支持,而不是iOS8