Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rotate 180 degree for an UIImageView, and rotate back with same route

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

like image 772
Wingzero Avatar asked Feb 11 '15 06:02

Wingzero


4 Answers

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);
like image 63
Wingzero Avatar answered Sep 30 '22 15:09

Wingzero


self.DashButton.imageView.transform = CGAffineTransformMakeRotation(M_PI);
self.DashButton.imageView.transform = CGAffineTransformMakeRotation(0);
like image 7
Si Fisher Avatar answered Sep 30 '22 15:09

Si Fisher


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?

like image 6
Maria Avatar answered Sep 30 '22 14:09

Maria


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
}
like image 4
Lance Samaria Avatar answered Sep 30 '22 13:09

Lance Samaria