Rotating view in iPhone app

When iPhone came out for the first time, I was amazed at how iPhone rotated safari web browser. I wondered how iPhone would rotate it and was not aware that not all iPhone applications are rotatable, but now I know how.

Let’s assume that we already have your own extended UIViewController class. UIViewController class has these two classes for the rotate feature:

1
2
3
4
5
6
7
-(BOOL)shouldAutorotateToInterfaceOrientation:
	(UIInterfaceOrientation)interfaceOrientation {
}
-(void)willRotateToInterfaceOrientation:
	(UIInterfaceOrientation)orientation
		duration:(NSTimeInterval)duration {
}

shouldAutorotateToInterfaceOrientation method. You simply just return “YES” so that the viewcontroller rotate its views automatically. The 2nd method “willRotateToInterfaceOrientation” is the one you want to implement.

Let’s say you already had one UIView object with white color background. When you rotated your iPhone or iPhone simulator to landscape orientation, the UIView would be rotated. However, the view wouldn’t fit the screen. To make the view to stretch to the all 4 edges of the screen, I would write something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
-(void)willRotateToInterfaceOrientation:
	(UIInterfaceOrientation)orientation
		duration:(NSTimeInterval)duration {
	CGRect appFrame;
	appFrame.origin = CGPointMake(0.0f, 0.0f);
	if ((orientation == UIInterfaceOrientationLandscapeLeft) ||
			(orientation == UIInterfaceOrientationLandscapeRight))
		appFrame.size = CGSizeMake(480.0f, 300.0f);
	else
		appFrame.size = CGSizeMake(320.0f, 460.0f);
 
	[contentView setFrame:appFrame];
}

As you can see, every time view gets rotated, you would need to use setFrame method to set the new frame with a new size and new origin.

  1. Thanks for the quick tutorial. It did not work perfectly for me, but the solution was to change the last line to:

    self.view.bounds = appFrame;

  2. Hello!!! Thanks…
    Thanks for this tutorial. My solution is the union from the trevelyan and the entry blog.

    self.view.bounds = appFrame;
    self.view.frame = appFrame;

    • king
    • October 20th, 2011 3:01am

    really the solution works fine..,
    thank you

  1. August 30th, 2010
    Trackback from : Dizzey.com