iPhone programming: how to switch to a landscape view at the moment of your choosing
Maybe someday, Apple will make it easy to rotate manually into a landscape view. But right now it’s been causing me enormous headache with hideous frames issues. Running an app in landscape the whole time is easy, but doing just some views in landscape is insane, especially if you’re trying to switch while in the middle of a navigation controller.
However I’ve found an easy solution which is to use a new window. Just reset the whole view problem. You can then fake out the navigation bar using the method of your preference. Here’s the bare bones. For me, I’m going from a tableView, click on an item and get a “results view”.
// In ResultsListController, a UITableView delegate:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
ResultsViewController * resultsViewController = [[[ResultsViewController alloc] initWithNibName:@"ResultsViewController" bundle:nil] autorelease];
resultsViewController._recordIndex = indexPath.row;
UIWindow * window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // this is a leak!
window.backgroundColor = [UIColor redColor]; // just for debugging
[window addSubview:resultsViewController.view];
[window makeKeyAndVisible];
}
Now ResultsViewController has its own NIB, and the view is set to be sideways in IB.
// In ResultsViewController
- (void)viewWillAppear:(BOOL)animated; {
// First rotate the screen:
[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationLandscapeRight;
// Then rotate the view and re-align it:
CGAffineTransform landscapeTransform = CGAffineTransformMakeRotation( degreesToRadian(90) );
landscapeTransform = CGAffineTransformTranslate( landscapeTransform, +90.0, +90.0 );
[self.view setTransform:landscapeTransform];
}
// Connect your "back" button in the results view to this:
- (IBAction)back:sender; {
// return screen rotation to normal:
[UIApplication sharedApplication].statusBarOrientation = UIInterfaceOrientationPortrait;
// Get rid of the window, and the "normal" window will re-appear from underneath
self.view.window.hidden = YES;
[self.view.window resignKeyWindow];
}
Easy as cake!
UPDATE: There’s follow-up Q&A on the iphonedevSDK forums.