SwiftyJD
SwiftyJD

Reputation: 5451

Make a button rotate counterclockwise using CGAffineTransform swift 3 syntax?

I'm trying to make a button rotate counterclockwise but for some strange reason it's rotating clockwise. I know the previous way to do it is by M_PI but it's been deprecated for swift 3 and replaced with CGFloat.pi. I've tried:

   self.loginButton.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)

but it still moves clockwise. Any idea what the syntax is to move counterclockwise?

Upvotes: 9

Views: 5751

Answers (1)

Maddy
Maddy

Reputation: 1668

The animation will always take the shortest way. Therefore CGFloat.pi and -CGFloat.pi animates in same position.

As we need anti-clockwise rotation we forcefully made it a shortest way by using this -(CGFloat.pi * 0.999).

UIView.animate(withDuration: 1.0, animations:{

self.loginButton.transform = CGAffineTransform(rotationAngle:-(CGFloat.pi * 0.999))

})

There is a better solution than this use CABasicAnimation for anticlockwise rotation.

let anticlockAnimation = CABasicAnimation(keyPath: "transform.rotation")
anticlockAnimation.fromValue = CGFloat.pi
anticlockAnimation.toValue = 0
anticlockAnimation.isAdditive = true
anticlockAnimation.duration = 1.0
self.loginButton.layer.add(anticlockAnimation, forKey: "rotate")
self.loginButton.transform = CGAffineTransform(rotationAngle: -CGFloat.pi)

Upvotes: 16

Related Questions