i6x86
i6x86

Reputation: 1627

CGAffineTransform revert the rotating direction

I'm rotating 360º a UIButton using this code:

self.btn.transform = CGAffineTransform(rotationAngle: (180.0 * CGFloat(M_PI)) / 180.0)
    self.btn.transform = CGAffineTransform(rotationAngle: (0.0 * CGFloat(M_PI)) / 180.0)

The problem is that it rotates from left to right and i want to invert the direction. I have tried using -M_PI, or -180 and other combinations, but without success. What am i doing wrong?

Upvotes: 6

Views: 8030

Answers (1)

David S.
David S.

Reputation: 6705

You can apply a negative transform to reverse the direction:

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

Undo it with:

self.btn.transform = CGAffineTransform.identity

Remember that the transform mutates the view but not the actual object. You don't have to "undo" it, you just replace it.

Here is some simple working playground code showing animation counter-clockwise:

import UIKit
import PlaygroundSupport

let view:UIView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
view.backgroundColor = UIColor.red
PlaygroundPage.current.liveView = view

let button = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 50))

button.backgroundColor = UIColor.white
view.addSubview(button)

UIView.animateKeyframes(withDuration: 2.0, delay: 0.0, options: .repeat, animations: {
    let rotation = -0.999*CGFloat.pi
    button.transform = CGAffineTransform(rotationAngle: rotation)
    print(rotation)
}, completion: nil)

The result is this:

animation

Upvotes: 18

Related Questions