Reputation: 67
I'm trying to change a constraint at a push of a button.
@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()
}
I have an error once both constraints are active. They won't deactivate:
[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)>
edit:
Everyone had the correct answer here, and it helped me greatly. I just accepted the one that had example code.
Thanks guys!
Upvotes: 0
Views: 418
Reputation: 100533
Every click causes a new conflict
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()
}
Upvotes: 2
Reputation: 1032
The issue here is the way the constraints are created. Each time you reference the constraints in the code, you're not referencing the actual constraint that sits on the object, but instead creating a new constraint and ultimately a conflict. The solution is to create NSLayoutConstraint objects within the View Controller for each of these scenarios and then modify the value of the NSLayoutConstraint .constant value. Finally, don't forget to call the "layoutIfNeeded()" function on the view controller.
Upvotes: 2