Unable to simultaneously satisfy constraints programmatically. Swift iOS
我试图按一下按钮来更改约束。
1 2 3 4 5 6 7 8 9 10 11 | @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] Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one
you don't want. Try this: (1) look at each constraint and try to
figure out which you don't expect; (2) find the code that added the
unwanted constraint or constraints and fix it.[shortened].bottom == [shortened].bottom - 46 (active)>
[shortened].bottom == [shortened].bottom - 16 (active)>
Will attempt to recover by breaking constraint
[shortened].bottom == [shortened].bottom - 16 (active)>
编辑:
每个人在这里都有正确的答案,这对我有很大帮助。我刚刚接受了带有示例代码的代码。
谢谢大家!
这里的问题是创建约束的方式。每次在代码中引用约束时,您都不会引用位于对象上的实际约束,而是创建新的约束,最终导致冲突。解决方案是在每种情况下在View Controller中创建NSLayoutConstraint对象,然后修改NSLayoutConstraint .constant值。最后,不要忘记在视图控制器上调用" layoutIfNeeded()"函数。
每次点击都会引起新的冲突
1 | var botCon:NSLayoutConstraint! |
//
1 2 | botCon = someTableView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -16) botCon.isActive = true |
//
1 2 3 4 5 6 7 8 9 | @IBAction func firstButton(_ sender: Any) { botCon.constant = -46 self.view.layoutIfNeeded() } @IBAction func secondButton(_ sender: Any) { botCon.constant = -16 self.view.layoutIfNeeded() } |