Latest on twitter from msanchezmora 
  • loading...

Two straightforward actions: Rotate and Animate UIViews

Posted: April 7th, 2010 | Author: | Filed under: Objective-C | Tags: , , | No Comments »

When adding subviews to a superview doing addSubview and then bringSubviewToFront, I have found that subviews do not autorotate accordingly, therefore I needed to do it programmatically. The next piece of code does a landscape rotation of a UIView to the left or to the right. Note that the UIView has to be resized and located accordingly. For that, I set up the bounds to 480×320 because I always expect a +90 or -90 degrees rotation.

  1.  
  2. #define DegreesToRadian(__ANGLE__) ((__ANGLE__) / 180.0 * M_PI)
  3.  
  4. void rotateLandscape(UIView *viewToRotate, BOOL left) {
  5. viewToRotate.transform = CGAffineTransformIdentity;
  6. if (left) viewToRotate.transform = CGAffineTransformMakeRotation(DegreesToRadian(-90));
  7. else      viewToRotate.transform = CGAffineTransformMakeRotation(DegreesToRadian(+90));
  8. viewToRotate.bounds = CGRectMake(0.0, 0, 480, 320);//resize the view
  9. viewToRotate.center = CGPointMake(160.0f, 240.0f); //set the position of the view
  10. }
  11.  

An example on how to use it is:

  1. rotateLanscape(appDelegate.mapController.view,TRUE);

The second common action, dealing with UIViews’ transitions on iPhone development, is to be able to set up an animation in the transition between views. The next code do that:

  1. void setUpAnimation(UIView *animateWindow, UIViewAnimationTransition transitionType, float duration) {
  2.  
  3. [UIView beginAnimations:@"Animation" context:nil];
  4. [UIView setAnimationDuration:duration ];
  5. [UIView setAnimationCurve:UIViewAnimationCurveLinear];
  6. [UIView setAnimationTransition: transitionType forView:animateWindow  cache:YES];
  7. [UIView commitAnimations];
  8. }

An example on how to use it is:

  1. setUpAnimation(appDelegate.window, UIViewAnimationTransitionCurlDown, 0.5);

Embedding these two actions into functions sounds like a good idea since they will be repeated throughout your application many times. Also these are basic versions, they could allow more complex animations and rotations but I leave that for another day.

Post to Twitter