[英]Unable to simultaneously satisfy constraints programmatically. Swift iOS
我试图按一下按钮来更改约束。
@IBAction func firstButton(_ sender: Any) {
someTableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -16).isActive = false
someTableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -46).isActive = true
someTableView.updateConstraints()
}
@IBAction func secondButton(_ sender: Any) {
someTableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -46).isActive = false
someTableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -16).isActive = true
someTableView.updateConstraints()
}
一旦两个约束都激活,我就会出错。 他们不会停用:
[LayoutConstraints]无法同时满足约束。 以下列表中至少有一个约束是您不想要的约束。 尝试以下操作:(1)查看每个约束,并尝试找出不期望的约束; (2)查找添加了一个或多个不必要约束的代码并进行修复。
[shortened] .bottom == [shortened] .bottom-46(活动)>
[shortened] .bottom == [shortened] .bottom-16(活动)>
将尝试通过打破约束来恢复
[shortened] .bottom == [shortened] .bottom-16(活动)>
编辑:
每个人在这里都有正确的答案,它对我有很大的帮助。 我刚刚接受了带有示例代码的代码。
多谢你们!
这里的问题是创建约束的方式。 每次在代码中引用约束时,您并不是在引用位于对象上的实际约束,而是创建新的约束,最终导致冲突。 解决方案是在每种情况下在View Controller中创建NSLayoutConstraint对象,然后修改NSLayoutConstraint .constant值。 最后,不要忘记在视图控制器上调用“ layoutIfNeeded()”函数。
每次点击都会引起新的冲突
var botCon:NSLayoutConstraint!
//
botCon = someTableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -16)
botCon.isActive = true
//
@IBAction func firstButton(_ sender: Any) {
botCon.constant = -46
self.view.layoutIfNeeded()
}
@IBAction func secondButton(_ sender: Any) {
botCon.constant = -16
self.view.layoutIfNeeded()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.