UIView动画是iOS开发中常用的动画实现方式,通过animate(withDuration:animations:completion:)
方法可以创建简单的视图动画。其中completion回调参数用于在动画完成后执行某些操作。
当使用UIView动画时,有时会发现completion回调中的finished
参数始终为true,即使动画被中断或取消。
let animation = CABasicAnimation(keyPath: "position")
animation.fromValue = oldPosition
animation.toValue = newPosition
animation.duration = 1.0
animation.delegate = self
layer.add(animation, forKey: "positionAnimation")
// 实现CAAnimationDelegate
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
// flag会正确反映动画是否完成
}
let animator = UIViewPropertyAnimator(duration: 1.0, curve: .linear) {
// 动画代码
}
animator.addCompletion { position in
// position会反映动画状态:.end表示完成,.start表示未完成
}
animator.startAnimation()
UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: [], animations: {
UIView.addKeyframe(withRelativeStartTime: 0.0, relativeDuration: 0.5) {
// 第一阶段动画
}
UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
// 第二阶段动画
}
}, completion: { finished in
// finished参数会更准确
})
通过以上方法,可以更准确地获取动画的真实完成状态,而不是始终为true的completion参数。
没有搜到相关的文章