animate rotation UIImageView in swift

后端 未结 10 2272
抹茶落季
抹茶落季 2021-02-06 23:11

I\'m trying to animate a rotation of 180 degrees of a UIImageView in Swift

    UIView.animateWithDuration(1.0, animations: { () -> Void in
              


        
10条回答
  •  后悔当初
    2021-02-06 23:37

    ======= Extension for UIView =======

    I found this answer from the Internet, and I test it, working perfectly fine. Hope this will help to any one, just change the UIView to your need such as, UIView, UIButton, UIImageView, etc. and access with the myUIView.rotate() function, here myUIView should be replace with your View name (IBOutlet -> name) with correct view type for extension. This is the link that I found this answer. And this method is easy and working!

    === SWIFT 3 / 4 ===

    extension UIView{
        func rotate() {
            let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotation.toValue = NSNumber(double: M_PI * 2)
            rotation.duration = 1
            rotation.cumulative = true
            rotation.repeatCount = FLT_MAX
            self.layer.addAnimation(rotation, forKey: "rotationAnimation")
        }
    }
    

    suggested improvements. Thanks for all suggestions.

    === SWIFT 5 ===

    extension UIView{
        func rotate() {
            let rotation : CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
            rotation.toValue = NSNumber(value: Double.pi * 2)
            rotation.duration = 1
            rotation.isCumulative = true
            rotation.repeatCount = Float.greatestFiniteMagnitude
            self.layer.add(rotation, forKey: "rotationAnimation")
        }
    }
    

    And then call that extension like follow:

    self.your_UIViewOutletName_myUIView_here.rotate()
    

提交回复
热议问题