0

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!

1
  • 4
    you should keep a reference of your constraint and simply changing the constant will fix your issue Commented Aug 17, 2018 at 18:49

2 Answers 2

2

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()
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.