【问题标题】:Unable to simultaneously satisfy constraints programmatically. Swift iOS无法以编程方式同时满足约束。斯威夫特 iOS
【发布时间】:2019-01-24 20:08:27
【问题描述】:

我正在尝试通过按一下按钮来更改约束。

@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) 找到添加的代码 不需要的约束或约束并修复它。

[缩短].bottom == [缩短].bottom - 46(活动)>

[shortened].bottom == [shortened].bottom - 16(活动)>

将尝试通过打破约束来恢复

[shortened].bottom == [shortened].bottom - 16(活动)>

编辑:

这里大家都答对了,对我帮助很大。我刚刚接受了有示例代码的那个。

谢谢大家!

【问题讨论】:

  • 您应该保留对约束的引用,只需更改常量即可解决您的问题

标签: ios swift constraints nslayoutconstraint


【解决方案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()
}

【讨论】:

    【解决方案2】:

    这里的问题是创建约束的方式。每次引用代码中的约束时,您都不是在引用对象上的实际约束,而是创建一个新的约束并最终产生冲突。解决方案是在每个场景的 View Controller 中创建 NSLayoutConstraint 对象,然后修改 NSLayoutConstraint .constant 的值。最后,别忘了在视图控制器上调用“layoutIfNeeded()”函数。

    【讨论】:

      猜你喜欢
      • 2023-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多