[英]AutoLayout not updating views programmatically - Swift
我有以下代码,我在其中创建和布置代码中的所有内容。 我想要做的是在点击按钮时修改myTopContainer
但我不能改变宽度,只有高度被修改。
知道为什么吗?
func setupAutoLayout(){
NSLayoutConstraint.activate([
// My Container
myTopContainer.bottomAnchor.constraint(equalTo: myButton.topAnchor, constant: -5),
myTopContainer.heightAnchor.constraint(equalToConstant: 50),
myTopContainer.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 15),
myTopContainer.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -15),
// My Button
myButton.widthAnchor.constraint(equalToConstant: 80),
myButton.heightAnchor.constraint(equalToConstant: 40),
myButton.trailingAnchor.constraint(equalTo: self.view.trailingAnchor, constant: -15),
myButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor, constant: -400)
])
}
@IBAction func relayoutViews(_ sender: Any) {
UIView.animate(withDuration: 0.5, delay: 0, options: .curveEaseIn, animations: {
self.myTopContainer.heightAnchor.constraint(equalToConstant: 50).isActive = false
self.myTopContainer.leadingAnchor.constraint(equalTo: self.view.leadingAnchor, constant: 15).isActive = false
// this is working, it changes the height
self.myTopContainer.heightAnchor.constraint(equalToConstant: 10).isActive = true
// this is not doing anything
self.myTopContainer.leadingAnchor.constraint(equalTo: self.myButton.trailingAnchor).isActive = true
self.view.layoutIfNeeded()
})
}
像这样的一行
self.myTopContainer.heightAnchor.constraint(equalToConstant: 50).isActive = false
每次创建一个新的约束。 它不会修改先前创建的约束。
当您 setupAutolayout 时,您应该在实际调用NSLayoutConstraint.activate()
之前保存对稍后要修改的约束的引用。 稍后您可以在它们上将 isActive 设置为 false。
例如:
var someConstraint: NSLayoutConstraint?
func setupAutoLayout(){
let aConstraint = myTopContainer.bottomAnchor.constraint(equalTo: myButton.topAnchor, constant: -5)
someConstraint = aConstraint
NSLayoutConstraint.activate([
// My Container
aConstraint
])
}
func editConstraint() {
self.someConstraint?.isActive = false
}
无论如何,当你编辑约束时要小心日志,你可能会在编辑时破坏一些东西。 如果您看到那些破坏约束的日志,则意味着仍然有问题(即使看起来不错,它也可能在其他情况下崩溃或无法正常工作)
你错过了:
view.translatesAutoresizingMaskIntoConstraints = false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.