9

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?

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • 1
    See the discussion here: http://stackoverflow.com/questions/21761184/catransaction-rotate-layer-360-degree-strange You need to use core animation. – matt May 18 '17 at 03:24
  • You may have forgot to accept the answer given here. It worked perfectly for me. – Declan McKenna Oct 27 '20 at 13:59

1 Answers1

16

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)
Maddy
  • 1,660
  • 11
  • 24