以编程方式调整约束是否需要先删除它们然后重新添加?

时间:2016-04-19 03:48:51

标签: ios swift autolayout

我的代码中有一个函数可以调整某些按钮的布局。设置.hidden时会调用此方法。

   private func layoutButtons() {

        redButton.hidden = !redButtonEnabled
        redButtonLabel.hidden = !redButtonEnabled
        yellowButton.hidden = !yellowButtonEnabled
        yellowButtonLabel.hidden = !yellowButtonEnabled

        removeConstraint(yellowButtonTrailingContraint)
        if yellowButtonEnabled && !redButtonEnabled {
            yellowButtonTrailingContraint = NSLayoutConstraint(item: yellowButton, attribute: .Trailing, relatedBy: .Equal, toItem: self, attribute: .Trailing, multiplier: 1.0, constant: -horizontalMargin)
        } else {
            yellowButtonTrailingContraint = NSLayoutConstraint(item: yellowButton, attribute: .Trailing, relatedBy: .Equal, toItem: redButton, attribute: .Leading, multiplier: 1.0, constant: -horizontalMargin)
        }
        addConstraint(yellowButtonTrailingContraint)
    }

在更改约束之前是否有必要先删除约束,然后像我上面那样重新添加约束?在某个地方看到这个例子,但看起来有点奇怪。关于这一点的指示将非常感激。谢谢!

1 个答案:

答案 0 :(得分:3)

是的,删除约束是一种选择,但并不总是必要的。

您有时可以通过更改其常量值来编辑约束,这将更新布局。 例如:

    var constraintHeight1 = NSLayoutConstraint(item: someView, attribute: .Height, relatedBy:.Equal, toItem:nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
    var constraintHeight2 = NSLayoutConstraint(item: someView, attribute: .Height, relatedBy:.Equal, toItem:nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 200)
    constraintHeight1.active = true
    constraintHeight2.active = false

    someView.addConstraint(constraintHeight1)
    someView.addConstraint(constraintHeight2)

    ...
    //Later you can set the other constraint as active
    constraintHeight1.active = false
    constraintHeight2.active = true
    someView.layoutIfNeeded()

或者您可以激活或停用它们,例如:

class Company(models.Model):
    STATUS_CHOICES=(
                    ('service','service'),
                    ('product','product'),
    )
    user=models.OneToOneField(settings.AUTH_USER_MODEL)
    company_name=models.CharField(max_length=250)
    company_address=models.CharField(max_length=250)
    Company_telephone=models.CharField(max_length=250,blank=True)
    company_email=models.CharField(max_length=250,blank=True)
    company_website=models.CharField(max_length=250,blank=True)
    VAT=models.CharField(max_length=250,blank=True)
    Service_Tax=models.CharField(max_length=250,blank=True)
    company_PAN=models.CharField(max_length=250,blank=True)
    company_bankdetails=models.CharField(max_length=250,blank=True)
    invoice_type=models.CharField(max_length=250,choices=STATUS_CHOICES,default='service')

    def __str__(self):
        return 'self.user.company_name'

在任何给定点,只有活动约束将用于决定视图的最终布局。所以,你有几个选择,但我们必须确保永远不会有两个冲突的约束是活跃的,否则应用程序将崩溃。我们将不得不删除其中一个冲突的约束或停用它。希望它有所帮助:]