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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With