In iOS, the coordinate system is flipped. So you go clockwise as your degree gains. It means that passing 270° will give you an angle, equivalent to 90° in the standard coordinate system. Keep that in mind and provide needed angle accordingly.
Consider the following approach.
1) Handy extension for angle
postfix operator °
protocol IntegerInitializable: ExpressibleByIntegerLiteral {
init (_: Int)
}
extension Int: IntegerInitializable {
postfix public static func °(lhs: Int) -> CGFloat {
return CGFloat(lhs) * .pi / 180
}
}
extension CGFloat: IntegerInitializable {
postfix public static func °(lhs: CGFloat) -> CGFloat {
return lhs * .pi / 180
}
}
2) Rotate to any angle with CABasicAnimation:
extension UIView {
func rotateWithAnimation(angle: CGFloat, duration: CGFloat? = nil) {
let pathAnimation = CABasicAnimation(keyPath: "transform.rotation")
pathAnimation.duration = CFTimeInterval(duration ?? 2.0)
pathAnimation.fromValue = 0
pathAnimation.toValue = angle
pathAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
self.transform = transform.rotated(by: angle)
self.layer.add(pathAnimation, forKey: "transform.rotation")
}
}
Usage:
override func viewDidAppear(_ animated: Bool) {
// clockwise
myView.rotateWithAnimation(angle: 90°)
// counter-clockwise
myView.rotateWithAnimation(angle: -270°)
}
Passing negative value will rotate counter-clockwise.