如何以程序方式为可变数量的UIView设置约束条件

3

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

Image flow

如果只有一个按钮,则该按钮会水平居中显示。 如果启用了两个按钮,则第二行将显示在与三个图像相同的图像中。

Stack View 是实现这种效果的最佳方式,但它仅支持 iOS 8 及以上版本。 - Jaimish
UIStackView自iOS9开始提供,而不是iOS8。 - Luca Bartoletti
2个回答

1
我的方法是在开始时将所有按钮的centerX设置为父视图的centerX>。
IBOutletCollection(UIButton) NSArray *allButtons;
//3 buttons' references
IBOutletCollection(NSLayoutConstraint) NSArray *allButtonCenterConstraints;
//buttons' centerX constraints' references

然后如果在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];

如果您需要根据按钮宽度设置某些内容,您可以根据按钮的宽度设置常量。


0

在以编程方式设置约束之后,创建约束插座

例如:

@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

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接