Swift: UILabel 的动画旋转

Swift: Animate rotation of UILabel

let turnIndicator = UILabel(frame: CGRectMake(0, 0, 50, 50))
turnIndicator.alpha = 1
turnIndicator.backgroundColor = UIColor.clearColor()
turnIndicator.layer.backgroundColor = UIColor(red: 31/255.0, green: 174/255.0, blue: 240/255.0, alpha: 1.0).CGColor
turnIndicator.textColor = UIColor.blackColor()
turnIndicator.layer.cornerRadius = 25
turnIndicator.layer.borderColor = UIColor(red: 31/255.0, green: 174/255.0, blue: 240/255.0, alpha: 1.0).CGColor
turnIndicator.layer.borderWidth = 1
turnIndicator.textAlignment = NSTextAlignment.Center
turnIndicator.text = "↓"
currentView.view.addSubview(turnIndicator)

let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation")
rotationAnimation.fromValue = 0.0
rotationAnimation.toValue = M_PI
rotationAnimation.duration = 1.0

turnIndicator.layer.addAnimation(rotationAnimation, forKey: nil)

我试过这段代码来旋转我的 UILabel,但它没有用,我有另一个代码来做旋转动画,它旋转成功但没有动画。

谢谢!

你可以使用UIView.animateWithDuration,像这样:

UIView.animateWithDuration(3) { () -> Void in
      self.turnIndicator.layer.transform = CATransform3DMakeRotation(CGFloat(M_PI), 0, 0, 1);
}

UIView.animateWithDuration 文档 here

CATransform3DMakeRotation 文档 here

像这样使用AnimateWithDuration

UIView.animateWithDuration(3/ 2, delay: 0, options: .Autoreverse, animations: {() -> Void in

var transform: CGAffineTransform = CGAffineTransformMakeRotation(M_PI)
    switchButton.transform = transform

}, completion: {(finished: Bool) -> Void in

    var transform: CGAffineTransform = CGAffineTransformIdentity
    switchButton.transform = transform
})