Swift_Dev
Swift_Dev

Reputation: 204

Rotate an UIView with CGAffineTransformMakeRotation

I use the following code to rotate my UIView to 90 degrees.

    - (IBAction)rotateView:(id)sender {

    [UIView animateWithDuration:0.2 animations:^{
        _myView.transform = CGAffineTransformMakeRotation(M_PI/2);
    }]; 
}

If I call rotateView action again, _myView won't rotate again. Any ideas how can I fix that? I want to rotate _myView 90 degrees every time i call rotateView.

Upvotes: 1

Views: 730

Answers (2)

dfmuir
dfmuir

Reputation: 2088

When you add the transform to myView you are not applying a transform to it's existing transformed state, but rather overwriting the transform. This means that when you set transform = CGAffineTransformMakeRotation(M_PI/2) for the second time, you are not actually changing the transform at all.

EDIT: As Rob pointed out, there is no need to use the property rotationInRadians when the rotation value is already stored in the transform. Instead you can simply modify the existing transform like this:

[UIView animateWithDuration:0.2 animations:^{
    _myView.transform = CGAffineTransformRotate(_myView.transform, M_PI/2);
}];

Below is the not ideal solution that I previously presented.

You will need a variable that keeps track of your rotation. You will increment this variable by your desired amount each time you want to rotate, then create a new transform based on the new value of the variable.

Make a property to do this:

@property (nonatomic, assign) CGFloat rotationInRadians;

Initialize it to 0 in your init method. Then modify your rotateView method to increment rotationInRadians and apply the new transform.

- (IBAction)rotateView:(id)sender {
    self.rotationInRadians += M_PI/2;
    [UIView animateWithDuration:0.2 animations:^{
        _myView.transform = CGAffineTransformMakeRotation(self.rotationInRadians);
    }]; 
}

Upvotes: 0

rob mayoff
rob mayoff

Reputation: 385500

[UIView animateWithDuration:0.2 animations:^{
    _myView.transform = CGAffineTransformRotate(_myView.transform, M_PI/2);
}]; 

Upvotes: 2

Related Questions