Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIView Rotation can't happen twice

In my UITableViewCell I have UIImageView which i want to rotate for 180° every time user clicks the row (didSelectRowAtIndexPath:). Code is pretty simple :

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
 {
     UITableViewCell *curCell = [self.tableView cellForRowAtIndexPath:indexPath];
     UIImageView *imgArrow = (UIImageView*)[curCell viewWithTag:3];
     [UIView animateWithDuration:0.3 animations:^{imgArrow.transform = CGAffineTransformMakeRotation(M_PI);}];
 }

The problem is that this always happens only once - the first time user clicks cell, imgArrow is rotated properly, but it wont rotate back when cell is clicked for second time. why?

Thanks for help!

like image 424
animal_chin Avatar asked Aug 27 '12 14:08

animal_chin


2 Answers

The problem is that the views transform property rotates to the degree specified from the views original transform. So Once your button is rotated 180 degrees calling this again will do nothing because it will attempt to rotate from where it currently is (180) to 180.

This being said, you need to make an if statement to check the transform. If it is 180 set the rotating to "0" and vice versa.

An easy way to achieve this would be using a BOOL.

if (shouldRotate){
     [UIView animateWithDuration:0.3 animations:^{imgArrow.transform = CGAffineTransformMakeRotation(M_PI);}];
     shouldRotate = NO;
}else{
     [UIView animateWithDuration:0.3 animations:^{imgArrow.transform = CGAffineTransformMakeRotation(0);}];
     shouldRotate = YES;
}
like image 154
Mick MacCallum Avatar answered Oct 13 '22 21:10

Mick MacCallum


You are just setting the transformation. To apply multiple transformations, you must multiply the imgArrow.transform transformation matrix by the desired new transformation. You can use CGAffineTransformConcat() to do this.

CGAffineTransform currTransform = [imgArrow transform];
CGAffineTransform newTransform = CGAffineTransformConcat(currTransform, CGAffineTransformMakeRotation(M_PI));
[imgArrow setTransform:newTransform];
like image 24
Alexander Avatar answered Oct 13 '22 19:10

Alexander