Change iPhone/iPod app orientation within a UITabBarController
The documentation for the official iPhone SDK is less than stellar, and as a result I’ve encountered lots of frustrating little problems. In particular, I wasn’t able to get my app to change its orientation when the phone was rotated.
UIViewController has a method
shouldAutorotateToInterfaceOrientation: that gets called when the iPhone/iPod orientation is changed by the user, and overriding this method to return
YES should cause your view to be rotated. You may have implemented this method and to your frustration, nothing happened when you rotated the device. The trick is that Cocoa only calls
shouldAutorotateToInterfaceOrientation: on the top most
UIViewController. Meaning if your program lives inside a
UITabBarController (possibly with a
UINavigationController inside some of the tab bar items), the
UIViewController that the user is currently interacting with, is not necessarily the one receiving the method call.
In my app, everything lives inside a
UITabBarController, so that’s what was receiving the
shouldAutorotateToInterfaceOrientation: call. In order to get orientation changes to work you need to subclass
UITabBarController (contrary to Apple doc recommendations) and override the method so you can return
YES when it’s called. Below is some code for a simple
UITabBarController subclass used inside a program that supports a horizontal view.
The one thing this doesn’t address, is when you only want certain views in your program to rotate. In that case you just need to make your
UITabBarController ask the currently visible view controller in the program if the app should rotate, and return that