1

I try to perform a layout update, with following lines, but animation is prompt, there is no delay. Any idea why? Using 8.0 Xcode.

UIView.animate(withDuration: 12.0, animations: {

    self.yellowLineLeadingConstraint.isActive = false
    self.yellowLineTrailingConstraint.isActive = false

    self.yellowLineLeadingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .leading, relatedBy: .equal, toItem: b, attribute: .leading, multiplier: 1.0, constant: 0)
    self.yellowLineTrailingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .trailing, relatedBy: .equal, toItem: b, attribute: .trailing, multiplier: 1.0, constant: 0)

    self.view.addConstraints([self.yellowLineLeadingConstraint, self.yellowLineTrailingConstraint])

    self.yellowLineLeadingConstraint.isActive = true
    self.yellowLineTrailingConstraint.isActive = true
})
János
  • 32,867
  • 38
  • 193
  • 353

2 Answers2

4

The proper way to animate layout constraints is to change them beforehand, and call layoutIfNeeded in your animation block (this tells the view to actually update its layout). So your code would look like this:

self.yellowLineLeadingConstraint.isActive = false
self.yellowLineTrailingConstraint.isActive = false

self.yellowLineLeadingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .leading, relatedBy: .equal, toItem: b, attribute: .leading, multiplier: 1.0, constant: 0)
self.yellowLineTrailingConstraint = NSLayoutConstraint(item: self.yellowLine, attribute: .trailing, relatedBy: .equal, toItem: b, attribute: .trailing, multiplier: 1.0, constant: 0)

self.view.addConstraints([self.yellowLineLeadingConstraint, self.yellowLineTrailingConstraint])

self.yellowLineLeadingConstraint.isActive = true
self.yellowLineTrailingConstraint.isActive = true

UIView.animate(withDuration: 12.0, animations: {
    self.view.layoutIfNeeded()
}
Connor Neville
  • 7,291
  • 4
  • 28
  • 44
-2

You aren't changing any "animatable" attributes. I see you are updating your constraint attribute, but it's not one of these Animatable Properties

Jon Whitmore
  • 267
  • 1
  • 2
  • 8
  • This is not true, you can animate constraint changes. https://stackoverflow.com/questions/12622424/how-do-i-animate-constraint-changes – Kane Cheshire Jul 15 '17 at 17:51