【问题标题】:How to set constraints programmatically for a varying number of UIView如何以编程方式为不同数量的 UIView 设置约束
【发布时间】:2016-02-12 06:58:57
【问题描述】:

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

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

【问题讨论】:

  • 堆栈视图是这样做的最好方法,但它只支持在 ios 8 之后
  • UIStackView 从 iOS9 开始可用,而不是 iOS8

标签: ios objective-c iphone autolayout nslayoutconstraint


【解决方案1】:

我的方法是在开头将所有按钮centerX设置为superview的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];

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

【讨论】:

    【解决方案2】:

    在你务实地设置约束之后制作约束出口

    喜欢:

    @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
    
        }
    

    【讨论】:

      猜你喜欢
      • 2013-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2016-08-07
      相关资源
      最近更新 更多