简体   繁体   中英

Unable to simultaneously satisfy constraints programmatically. Swift iOS

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!

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM