iosswiftuikituiviewpropertyanimator

UIViewPropertyAnimator completion called when paused


I haven’t used UIViewPropertyAnimator very much (still an old fashioned blocks guy) and I’m seeing some behavior that I can’t explain and that the docs don’t really provide any insight on.

Why does an animator’s completion block get called with a finalPosition of .end even when the animator is paused immediately after it’s started?

let view = UIView()
let animator = UIViewPropertyAnimator(duration: 4, curve: .linear, animations: {
    view.alpha = 0
})

animator.addCompletion { position in
    print("done")
    switch position {
    case .start: print("start")
    case .current: print("current")
    case .end: print("end")
    }
}

animator.startAnimation()
print("starting")
animator.pauseAnimation()
print("pausing")

Output:

starting
pausing
done
end

Solution

  • The problem, as @matt alluded to, is that your view isn't in a visible UIWindow, so the animations complete immediately. You get the same output if you comment out the animator.pauseAnimation() statement.

    You can fix this if you're using a playground by making view the liveView of the playground page:

    import PlaygroundSupport
    import UIKit
    
    let view = UIView()
    PlaygroundPage.current.liveView = view
    
    // etc.