gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 11:07:45 25 4
gpt4 key购买 nike

我的代码中有一个函数可以调整某些按钮的布局。这在设置 .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)
}

是否有必要在更改约束之前首先删除约束,然后像我上面所做的那样在之后重新添加它?在某处的示例中看到了这一点,但看起来有点奇怪。对此的指点将不胜感激。谢谢!

最佳答案

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

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

    var constraintHeight = NSLayoutConstraint(item: someView, attribute: .Height, relatedBy:.Equal, toItem:nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 100)
someView.addConstraint(constraintHeight)
...
//The Constraint can be edited later by changing the constant value
constraintHeight.constant = 200
someView.layoutIfNeeded()

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

    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()

在任何给定点,只有事件约束将用于决定 View 的最终布局。因此,您几乎没有其他选择,但我们必须确保永远不会有两个相互冲突的约束处于事件状态,否则应用程序将崩溃。我们将不得不删除其中一个冲突约束或将其停用。希望对您有所帮助:]

关于ios - 以编程方式调整约束是否需要先删除然后重新添加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36708212/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com