14

How to programmatically rotate the view by 180 degrees in my iPhone App?

Cœur
  • 37,241
  • 25
  • 195
  • 267
meetpd
  • 9,150
  • 21
  • 71
  • 119

7 Answers7

36

As ’CGAffineTransformRotate’ uses radians as its unit of measure, and 180 degrees is the same as PI, instead of the math provided in other answers you can simply do:

view.transform = CGAffineTransformRotate(view.transform, M_PI);

Swift 3:

view.transform = view.transform.rotated(by: .pi)

If you plan on doing a lot of transforms, it's probably best to read up on radians, so you understand what is going on.

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
Benjamin Mayo
  • 6,649
  • 2
  • 26
  • 25
14

Should be possible by using CGAffineTransform

Quote from this question, this should do the trick:

CGFloat radians = atan2f(yourView.transform.b, yourView.transform.a);
CGFloat degrees = radians * (180 / M_PI);
CGAffineTransform transform = CGAffineTransformMakeRotation((90 + degrees) * M_PI/180);
yourView.transform = transform;
Community
  • 1
  • 1
Manny
  • 6,277
  • 3
  • 31
  • 45
  • 1
    This rotates it 90 degrees. If you want it to rotate it by 180 degrees, they last line should be `CGAffineTransformMakeRotation((` **180** `+ degrees) * M_PI/180)` instead of 90 – Eliza Wilson May 14 '14 at 00:39
8

Swift 4:

self.view.transform = CGAffineTransform(rotationAngle: .pi);

And a COMMENT (I evidently don't have enough points to enter my comment on his/her answer) for Benjamin Mayo or vtcajones answer of:

view.transform = view.transform.rotated(by: .pi)

This will work the first time, but the next time it is called it will rotate the view again, back to the original rotation, which is probably not what you want. It would be safer to set the transform value exactly each time.

ByteSlinger
  • 1,439
  • 1
  • 17
  • 28
6

Simple solution:

view.transform = CGAffineTransformMakeRotation(degrees*M_PI/180);
Just Shadow
  • 10,860
  • 6
  • 57
  • 75
Ram Vadranam
  • 485
  • 5
  • 14
5

In Swift 3 :

let rotationDegrees =  180.0
let rotationAngle = CGFloat(rotationDegrees * M_PI / 180.0)
view.transform = CGAffineTransform(rotationAngle: rotationAngle)
Wilson
  • 9,006
  • 3
  • 42
  • 46
4

Same outcome as @Manny's answer using a different function.

 CGFloat degreesOfRotation = 180.0;
 view.transform = CGAffineTransformRotate(view.transform,
     degreesOfRotation * M_PI/180.0);
cbay
  • 72
  • 7
thealch3m1st
  • 282
  • 1
  • 4
  • 11
1

Latest Swift 3 syntax:

view.transform = view.transform.rotated(by: .pi)
vtcajones
  • 1,700
  • 2
  • 13
  • 9