ios 在 Swift 中以编程方式更新约束的常量属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28127259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 04:29:17  来源:igfitidea点击:

Update the constant property of a constraint programmatically in Swift?

iosswiftnslayoutconstraint

提问by Cesare

I want to animate an object, so I declare a constraint and add it to the view. I then update the constantproperty of the constraint inside an UIViewanimation. Why doesn't this code move the object?

我想为一个对象设置动画,所以我声明了一个约束并将其添加到视图中。然后我更新动画中constant约束的属性UIView。为什么这段代码不移动对象?

UIView.animateWithDuration(1, animations: {
     myConstraint.constant = 0   
     self.view.updateConstraints(myConstraint)
})

回答by duan

In order to declare an animation, you cannot re-define the constraint and call updateConstraints. You are supposed to change the constantof your constraint and follow the format below:

为了声明动画,您不能重新定义约束并调用updateConstraints. 您应该更改constant约束并遵循以下格式:

self.view.layoutIfNeeded()
UIView.animate(withDuration: 1) {
    self.sampleConstraint.constant = 20
    self.view.layoutIfNeeded()
}