如何使用UIViewPropertyAnimator旋转360º

时间:2016-12-16 10:41:37

标签: ios swift animation

如果我想通过UIViewPropertyAnimator利用用户互动动画,如何将对象顺时针旋转360º?

// Does not animate
let animator = UIViewPropertyAnimator(duration: 2, curve: .linear) {
    let radians = Angle(360).radians // 6.28318530717959
    view.transform = view.transform.rotated(by: CGFloat(radians))
}
// (Using RxSwift to handle the user interaction via UISlider, 
// but that can be ignored as an implementation detail for this question.)
let scrubs = slider.rx.value.asDriver()
scrubs.drive(onNext: { (value:Float) -> Void in
    animator.fractionComplete = CGFloat(value)
})

1 个答案:

答案 0 :(得分:3)

幸运的是,UIViewPropertyAnimator使这个变得非常简单(如果不是有点hackish?)。只需制作两个动画,每个动画为180º。:

let animator = UIViewPropertyAnimator(duration: 2, curve: .linear) {
    let radians = Angle(180).radians // 3.14159265358979
    view.transform = view.transform.rotated(by: CGFloat(radians))
}
animator.addAnimations {
    let radians = Angle(180).radians
    view.transform = view.transform.rotated(by: radians)
}

这将像一个动画,可以通过fractionComplete启动,停止,暂停,完成或“擦除”。

Example playground