Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CGAffineTransform revert the rotating direction

Tags:

swift

swift3

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?

like image 763
i6x86 Avatar asked Mar 30 '17 16:03

i6x86


1 Answers

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

like image 116
David S. Avatar answered Sep 21 '22 00:09

David S.