Kobe Kobe - 29 days ago 12
iOS Question

UIImageView doesn't animate when using Auto Layout

My image has the following constraints:


  • leading = 0

  • trailing = 0

  • top = 75

  • height = 250



I want my image to start from the right side of the screen and move to initial place where the constraints are set.

Here is my code:

imageLeadingConstraint.constant = 100
imageTrailingConstraint.constant = -100
imageTopConstraint.constant = 100
image.layoutIfNeeded()

UIView.animate(withDuration: 1.0) {
self.imageLeadingConstraint.constant = 0
self.imageTrailingConstraint.constant = 0
self.imageTopConstraint.constant = 75
self.image.layoutIfNeeded()
}


The issue is that the image is moving to initial place, but not using an animation.

Is my code right ? How come the image just appears in the new position and not animating ?

Answer

You should call layoutIfNeeded for superview.

[self.image.superview layoutIfNeeded];