iosswiftuiviewconstraintscakeyframeanimation

Swift: Reset frame of a UIView to its constraints after animation


I am setting a UIImageView using constraints added programmatically in viewDidLoad.

Later on, after the user interacts with some buttons on the screen, I move the view by changing its frame using CAKeyframeAnimation with an array ofCGRect` values for the movement.

Now later in the app lifecycle, I'd like the UIImageView returned to where it was originally placed (using the constraints that I haven't changed). Is there a way to reset the frames to their initial constraints?


Solution

  • It's possible to revert to the original values using removeAnimation, doc here. So if use set your animation (let's say move) like:

    let animation = CAKeyframeAnimation()
    animation.keyPath = "position.y"
    animation.values = [0, 200]
    animation.keyTimes = [0, 1]
    animation.duration = 1
    animation.isAdditive = true
    animation.fillMode = kCAFillModeForwards
    animation.isRemovedOnCompletion = false
    innerView.layer.add(animation, forKey: "move")
    

    then whenever you need to revert, you might call:

    innerView.layer.removeAnimation(forKey: "move")