观察UIViewPropertyAnimator正在运行问题

时间:2018-04-24 08:13:26

标签: ios animation key-value-observing uiviewpropertyanimator

来自Apple文档pausesoncompletion

  

因为当此属性为true时未调用完成处理程序,所以您无法使用动画制作器的完成处理程序来确定动画何时完成运行。 相反,您可以通过观察isRunning属性来确定动画何时结束。

但我发现观察isRunning不起作用。 util i wathched WWDC 2017 - Session 230-Advanced Animations with UIKit,我知道我应该观察running

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

我的问题是:我在哪里可以找到令人兴奋的密钥路径,而不仅仅是这种情况。 THX〜

1 个答案:

答案 0 :(得分:1)

在Swift中,建议使用基于块的KVO API(可从Swift 4开始使用),它允许您以类型安全且编译时检查的方式观察属性:

// 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
}

请注意,密钥路径为\.isRunning,因为Swift中UIViewPropertyAnimator上的属性称为isRunning

这两者的好处是您不必知道给定属性的字符串是如何拼写的,并且更改的值与被观察的属性具有相同的类型。

请注意,在Objective-C中,此API不可用,因此the corresponding Objective-C documentation要求您观察“running”属性。这是因为在Objective-C中,属性被称为“running”(但是有一个名为“isRunning”的getter)。