animate rotation UIImageView in swift

后端 未结 10 2279
抹茶落季
抹茶落季 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:23

    Swift 5.0

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

    Updating to @Rakshitha Muranga Rodrigo answer.

    0 讨论(0)
  • 2021-02-06 23:25

    Be sure to be in the Main thread

    DispatchQueue.main.async {
       UIView.animateWithDuration(1.0, animations: { () -> Void in
         self.arrowImageView.transform = CGAffineTransformMakeRotation(CGFloat(180 * M_PI))
       }) { (succeed) -> Void in
    
       }
    }
    
    0 讨论(0)
  • 2021-02-06 23:27

    You left out the / 180 on CGFloat(180 * M_PI). Try:

    UIView.animate(withDuration: 1.0) {[weak self] in
        self?.arrowImageView.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
    }
    
    0 讨论(0)
  • 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()
    
    0 讨论(0)
提交回复
热议问题