I'm having difficulties removing and adding constraints programmatically with animation. I've simplified my existing project into a small project just for demonstration.
Setup is there are two (container) views: top and bottom. They contain two subviews: blue and red.
Top view has aspect ratio 2:3 constraint.

I have reference to topView, aspectRatioConstraint and heightConstraint which I initialize in viewDidLoad
@IBOutlet weak var aspectRatioConstraint: NSLayoutConstraint!
var heightConstraint: NSLayoutConstraint!
@IBOutlet weak var topView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
heightConstraint = NSLayoutConstraint(item: topView, attribute: .height, relatedBy: .equal, toItem: topView, attribute: .height, multiplier: 1.0, constant: topView.frame.size.height)
NSLayoutConstraint.activate([heightConstraint])
topView.removeConstraint(aspectRatioConstraint)
}
@IBAction func startAnimation(_ sender: AnyObject) {
UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
self.heightConstraint.constant = 20.0
self.view.layoutIfNeeded()
}, completion: nil)
}
"+" button in navigation calls startAnimation method and it should resize heightConstraint over period of time, but it doesn't.
What am I doing wrong?
Sample project -> https://www.dropbox.com/sh/7i75i0zq9dormqb/AACzTYvWOoJL3MjcjgMIyOd9a?dl=0
Try this :
UIView.animate(withDuration: 1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.1, options: .curveEaseIn, animations: {
NSLayoutConstraint.deactivate([self.heightConstraint])
self.heightConstraint.constant = 20.0
NSLayoutConstraint.activate([self.heightConstraint])
self.view.layoutIfNeeded()
}, completion: nil)
You have deactivate before updating some constraints
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