animate rotation UIImageView in swift

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

    Here is code to rotate imageview. swift 3.0

    UIView.animate(withDuration:2.0, animations: {
                self.dropDownImage.transform = CGAffineTransform(rotationAngle: CGFloat(imageRotation))
            })
    
    0 讨论(0)
  • 2021-02-06 23:15

    Try calling arrowImageView.layoutSubviews(), see below:

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

    90 degrees rotation

    var shouldRotateArrow = false {
        didSet {
            rotateArrow()
        }
    }
    
    private func rotateArrow() {
        let angle: CGFloat = shouldRotateArrow ? .pi / 2 : 0
        UIView.animate(withDuration: Constants.arrowRotationDuration) {
            self.arrowImageView.transform = CGAffineTransform(rotationAngle: angle)
        }
    }
    
    0 讨论(0)
  • 2021-02-06 23:19

    First of all, if you want to rotate 180 degrees, that has to translate to radians. 180 degrees in radians is pi. 360 degrees would be 2 * pi. 180 * pi would make your animation spin around 90 times in one second and end up with the original orientation.

    Secondly, I'm not sure why your code isn't working, but I know that the code below does work:

    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
    rotationAnimation.fromValue = 0.0
    rotationAnimation.toValue = M_PI
    rotationAnimation.duration = 1.0
    
    self.arrowImageView.layer.addAnimation(rotationAnimation, forKey: nil)
    
    0 讨论(0)
  • 2021-02-06 23:21

    For me the best and shortest solution is (Swift 3/4):

    self.YourImageView.transform = showing ? CGAffineTransform(rotationAngle: CGFloat.pi) : CGAffineTransform.identity
    

    "showing" it's a value to determine is image rotated before or not - you can use your own logic here

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

    Updated swift 4.0 version:

        let rotation: CABasicAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
        rotation.toValue = Double.pi * 2
        rotation.duration = 0.25 // or however long you want ...
        rotation.isCumulative = true
        rotation.repeatCount = Float.greatestFiniteMagnitude
        yourView.layer.add(rotation, forKey: "rotationAnimation")
    
    0 讨论(0)
提交回复
热议问题