Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS -AutoLayout constraint set active be crash in second time

I want to achieve a function that when I click the buttons ,the image will move between two button

I set a constraint between image and button2 (centerX,which text with 222) At the same time I set a constraint with button1(centerX,which text with 11) too and set the priority with 950 then I drag them to the viewcontroller

This is the constraint in my storyboard enter image description here

This is my code to control the constraint

if NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1 {

            self.kidLeftCenterConstrait.active = isLeft
            self.kidRightCenterConstrait.active = !isLeft
            UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
                self.view.layoutIfNeeded()
          })

       } else {
            let constraintToRemove = isLeft ? self.kidRightCenterConstrait : self.kidLeftCenterConstrait
            let constriaintToUse = isLeft ? self.kidLeftCenterConstrait : self.kidRightCenterConstrait
            self.douBi.superview!.removeConstraint(constraintToRemove)
            self.douBi.superview!.removeConstraint(constriaintToUse)
            self.douBi.superview!.addConstraint(constriaintToUse)
            UIView.animateWithDuration(kAnimationDuration, animations: { () -> Void in
            self.view.layoutIfNeeded()
      })
 }

After run in iphone I click the button1 the image move to the 11 ,then i click the button2 ,The application is cash in self.kidRightCenterConstrait.active = !isLeft

console log is fatal error:unexpectedly found nil while unwrapping an Optional value

like image 250
jansma Avatar asked Apr 27 '15 14:04

jansma


1 Answers

It appears the constraint get released. You might try to strongly retain your constraints:

@IBOutlet var kidLeftCenterConstrait: NSLayoutConstraint!
@IBOutlet var kidRightCenterConstrait: NSLayoutConstraint!

Anyway beware possible retain cycles. Check that your ViewController goes away when it's time has come.

I usually do this kind of animations managing the involved constraints all in code.

like image 189
Matteo Piombo Avatar answered Oct 13 '22 21:10

Matteo Piombo