iosanimationkey-value-observinguiviewpropertyanimator

Observing UIViewPropertyAnimator is running issue


From Apple Documents pausesoncompletion

Because the completion handler is not called when this property is true, you cannot use the animator's completion handler to determine when the animations have finished running. Instead, you determine when the animation has ended by observing the isRunning property.

But i found observe isRunning not work. util i wathched WWDC 2017 - Session 230-Advanced Animations with UIKit ,i konwed i should observe running

//not work
animator.addObserver(self, forKeyPath: "isRunning", options: [.new], context: nil)
//this work
animator.addObserver(self, forKeyPath: "running", options: [.new], context: nil)

My Question is: where can i find the excatly keypath, not only this case. Thx~


Solution

  • In Swift it's recommended to use the block-based KVO API (available as of Swift 4) which allows you to observe a property in a type safe and compile-time checked manner:

    // deinit or invalidate the returned observation token to stop observing
    let observationToken = animator.observe(\.isRunning) { animator, change in
        // Check `change.newValue` for the new (optional) value
    }
    

    Note that the key path is \.isRunning because the property on UIViewPropertyAnimator in Swift is called isRunning.

    This both has the benefit that you don't have to know how the string for a given property is spelled and that the changed value has the same type as the observed property.


    Note that in Objective-C this API is not available, so the corresponding Objective-C documentation ask you to observe the "running" property. This is because in Objective-C the property is called "running" (but has a getter called "isRunning").