[英]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.