0

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 https://stackoverflow.com/a/28717185/152825) but doesn't seem to have an effect. A

Community
  • 1
  • 1
timpone
  • 19,235
  • 36
  • 121
  • 211

1 Answers1

1

Try this:

if (isResultsOpen) {
      NSLayoutConstraint.deactivateConstraints([resultTopConstraint])
      NSLayoutConstraint.activateConstraints([newConstraint])
    } else {
      NSLayoutConstraint.deactivateConstraints([newConstraint])
      NSLayoutConstraint.activateConstraints([resultTopConstraint])
    }
timpone
  • 19,235
  • 36
  • 121
  • 211
Hazneliel
  • 531
  • 1
  • 5
  • 16
  • thx - that doesn't seem to do it (but a great suggestion). I have the strong feeling it is a valid constraint conflict. I'm not that experienced with autolayout so am probably doing something wrong. – timpone Jun 27 '16 at 17:18
  • Just updated my answer with another suggestion, tell me if that works – Hazneliel Jun 27 '16 at 17:36
  • I think that works! I had to put them in an array like `NSLayoutConstraint.deactivateConstraints([resultTopConstraint])` though. thx – timpone Jun 27 '16 at 18:17