timpone timpone - 5 months ago 24
iOS Question

can an NSLayoutConstraint be re-activated?

I have a result container that a user can expend and contract. I'd like to remove a constraint and add a new one. Clicking on it works fine but clicking a second time (ie setting newConstraint.active=false and resultTopConstraint=true causes it to crash). I have the following:

@IBAction func toggleResultContainer(sender: AnyObject) {

isResultsOpen = !isResultsOpen

//resultTopConstraint.constant = isResultsOpen ? -300.0 : 0.0

self.view.sendSubviewToBack(searchView)

let newConstraint = NSLayoutConstraint(
item: resultsContainer,
attribute: .Top,
relatedBy: .Equal,
toItem: resultsContainer.superview!,
attribute: .Top,
multiplier: 1.0,
constant: 30.0
)

if(isResultsOpen){
resultTopConstraint.active = false
newConstraint.active = true
}else{
resultTopConstraint.active = true
newConstraint.active = false
}

UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.4, initialSpringVelocity: 10.0, options: .CurveEaseIn, animations: {
self.view.layoutIfNeeded()
}, completion: nil)


and get the
Unable to simultaneously satisfy constraints.


Should the above code work and this is really a simultaneously satisfy constraints issue? I have tried setting the constraint

@IBOutlet var resultTopConstraint: NSLayoutConstraint!


to both
weak
and
strong
(per http://stackoverflow.com/a/28717185/152825) but doesn't seem to have an effect. A

Answer

Try this:

if (isResultsOpen) {
      NSLayoutConstraint.deactivateConstraints(resultTopConstraint)
      NSLayoutConstraint.activateConstraints(newConstraint)
    } else {
      NSLayoutConstraint.deactivateConstraints(newConstraint)
      NSLayoutConstraint.activateConstraints(resultTopConstraint)
    }
Comments