なんとかするから、なんとかなる

エンジニア関係のことを書きます

iOS How to rotate a UIView in 360 degrees.

Introduction

This article shows how to rotate360 degrees for UIView.

First I thought of using UiView.animate method and AffineTransform the UIView.

It was figured out that if I set a transform property as below

view.transform = CGAffineTransform(rotationAngle: CGFloat.pi * 2) 

But it’s not working because the animate method considered that the rotate was over immediately.

Second, I tried to set the property for CGFloat.pi*2-0.001.

But the UIView rotated a bit.

Solution

There are two solutions.

UIView.animate with completion

To write a method as below. And call it in its completion handler.

This rotate was weird. So it need to set a options or something.

func myAnimation() {
   UIView.animate(withDuration: 1.0, animations: {
       self.myView.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
   }) { (_) in
       UIView.animate(withDuration: 1.0, animations: {
           self.myView.transform = CGAffineTransform(rotationAngle: CGFloat.pi * 2)
        }, completion: { (_) in
           self.myAnimation()
       })
   }
}

QuartzCore

func rotation() {
    let rotateAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotateAnimation.toValue = CGFloat(CGFloat.pi * 2.0 * 2.0)
    rotateAnimation.duration = 2.0
    rotateAnimation.isCumulative = true
    rotateAnimation.repeatCount = 100
    myView.layer.add(rotateAnimation, forKey: "rotationAnimation")
}