无法通过编程同时满足约束。迅捷的iOS

时间:2018-08-17 18:40:27

标签: ios swift constraints nslayoutconstraint

我试图按一下按钮来更改约束。

@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(活动)>

编辑:

每个人在这里都有正确的答案,这对我有很大帮助。我刚刚接受了带有示例代码的代码。

谢谢大家!

2 个答案:

答案 0 :(得分:2)

这里的问题是创建约束的方式。每次在代码中引用约束时,您并不是在引用位于对象上的实际约束,而是创建新的约束,最终导致冲突。解决方案是在每种情况下在View Controller中创建NSLayoutConstraint对象,然后修改NSLayoutConstraint .constant值。最后,不要忘记在视图控制器上调用“ layoutIfNeeded()”函数。

答案 1 :(得分:1)

每次点击都会引起新的冲突

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