Dror Chen Dror Chen - 4 months ago 24
Swift Question

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)


I tried this code to rotate my UILabel, but it didn't work, i had another code to do the rotation animation, it rotated successfully but didn't animate it.

Thanks!

Answer

Yu can use UIView.animateWithDuration, like this:

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

UIView.animateWithDuration documentation here

CATransform3DMakeRotation documentation here

Comments