我想知道在哪种情况下我们应该最适合使用它们?
在下面的博客https://www.hackingwithswift.com/ios10中,即“重新访问动画”部分中编写的示例,我们是否可以使用“CABasicAnimation”重新应用相同的要求,即暂停和恢复动画?
从我收集到的信息来看,当我们使用UIView.animate(...)方法时,它返回一个void,因此我们将无法在动画完成之前对其进行控制,因为我们无法获得返回值来处理正如我们在UIViewPropertyAnimator中获得的一样(在这里,我们还有“isRunning”来检查动画的进度。)
同样在CABasicAnimation中,我们没有任何运行动画的进度检查。
如果我的假设是错误的,请纠正我。
谢谢。
最佳答案
TLDR
背景
所有这些API都很棒,而且它们的用例也略有不同。在进入他们之前,最好先了解一下
使用UIKit,动画使用
UIView
对象执行。可使用UIKit进行动画处理的属性有:frame
bounds
center
transform
alpha
backgroundColor
contentStretch
虽然Core Animation可以访问 View 的基础层,但可以公开如下所述的一组不同的属性(值得注意的是,由于 View 和图层之间的链接错综复杂,对 View 层的更改会影响 View 本身):
有关更多信息,请引用this Apple Developer document。
UIView的动画方法
我认为这些仍然是最容易使用的。非常简单的API,无需占用太多代码空间。我将其用于简单的“即忘即弃”动画(例如,在选择按钮时将其 pop ),或者在我想要制作复杂的关键帧动画时使用,因为它的关键帧支持很好。
例:
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseOut, animations: {
button.transform = .init(scaleX: 1.1, y: 1.1)
}
核心动画
也许使用起来不太直接,但是如上所述,每当要为图层属性而不是 View 属性设置动画时,都需要使用它。这些示例包括拐角半径,阴影和边框。
例:
CATransaction.begin()
CATransaction.setAnimationDuration(0.5)
CATransaction.timingFunction = .init(name: .easeOut)
let cornerAnimation = CABasicAnimation(keyPath: #keyPath(CALayer.cornerRadius))
cornerAnimation.fromValue = 0.0
cornerAnimation.toValue = 10.0
button.layer.add(cornerAnimation, forKey: #keyPath(CALayer.cornerRadius))
CATransaction.commit()
有关Core Animation的更多详细信息,this是一篇很棒的文章(不是我写的)。
UIViewPropertyAnimator
在iOS 10中添加,顾名思义,这是另一个基于 View 的动画API。有几件事使它不同于UIView的动画方法,主要是它支持交互式动画并允许动态修改动画。您可以暂停,倒带或擦洗动画,也可以随时随地添加更多动画块,或者在播放动画时反转动画,这使其功能非常强大。当我希望动画由用户控制时使用。通过在动画对象上设置
fractionComplete
属性,可以进行擦洗,可以轻松地将其挂接到平移手势识别器或强制触摸识别器(甚至使用KVO的键)上。如前所述,您还可以存储对
UIViewPropertyAnimator
的引用,并在动画过程中更改其动画或完成块。例:
// Create an animation object with an initual color change animation
let animator = UIViewPropertyAnimator(duration: duration, curve: .linear) {
button.backgroundColor = .blue
}
// At any point during the runtime, we can amend the list of animations like so
animator.addAnimations {
button.transform = .init(scaleX: 1.1, y: 1.1)
}
animator.startAnimation()
}
值得注意的是,如果您需要同时使用
UIView.animate
动画块,则可以实际使用UIView.animateKeyframes
和UIViewPropertyAnimator
。如果您想要
UIViewPropertyAnimator
的更详细的示例,我在here上写了一个小教程。
关于swift - 什么时候使用UIView动画,CABasicAnimation和UIViewPropertyAnimator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42802984/