I got a button and want to rotate the image inside it:
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(M_PI);
The image is a up-arrow to down-arrow after user click it When clicking the button again, I want the down-arrow rotate to up-arrow again, but it is the same counterclockwise rotation, but I just want the arrow reverse back to up-arrow
rotate back code:
self.DashButton.imageView.transform = CGAffineTransformIdentity;
I tried
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(-M_PI);
What I want is not rotate the full circle, just 180 rotate and -180 rotate, not a 360 full rotate
instead of -M_PI, use -3.14159. Kind of a trick, but below code saved my day.
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(M_PI);
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(M_PI - 3.14159);
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(M_PI);
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(0);
what you need is a negative angle to rotate it in the opposite direction
CGAffineTransformMakeRotation( 180 * CGFloat(M_PI/180))
CGAffineTransformMakeRotation(-1 * CGFloat(M_PI/180))
take a look at this answer for an explanation About CGAffineTransformMakeRotation rotation direction?
Swift 4 version of @Maria working answer
Rotate 180 degrees counter clockwise:
let transform = CGAffineTransform.identity
UIView.animate(withDuration: 0.3, animations: {
// to rotate counterclockwise set both of these in this exact order
self.button.transform = transform.rotated(by: 180 * CGFloat(Double.pi))
self.button.transform = transform.rotated(by: -1 * CGFloat(Double.pi))
}
Rotate back 180 degrees clockwise:
UIView.animate(withDuration: 0.3, animations: {
self.button.transform = CGAffineTransform.identity
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With