iOS 6 UINavigationControllerのAutorotate

プログラミング雑記: iOS 6 UINavigationControllerのAutorotate

iOS6ではshouldAutorotateToInterfaceOrientation:メソッドが廃止され、代わりにsupportedInterfaceOrientationsメソッドとshouldAutorotateメソッドを使うようになっています。 ところが最初のViewControllerをUINavigationControllerにしているアプリでは、他のViewControllerにこれらのメソッドを実装しても有効になりません。(shouldAutorotateが呼ばれない。) このようなアプリの場合は次のようにすると回転を制御できるようになります。 UINavigationControllerのサブクラスを作り、起動時のUINavigationControllerのクラスをそれに替える。 上記サブクラスにsupportedInterfaceOrientationsメソッドとshouldAutorotateメソッドを実装する。 一部の画面だけ縦・横の回転を行えうようにする場合、このサブクラスのsupportedInterfaceOrientationsが返す値を画面に応じて変更する。
実装例:
@interface MyNavigationController : UINavigationController
@end
@implementation MyNavigationController
- (NSUInteger)supportedInterfaceOrientations {
    if ([[self.viewControllers lastObject] isKindOfClass:[RotatableViewController class]]) {          return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {
        return UIInterfaceOrientationMaskPortrait;
    }
}
- (BOOL)shouldAutorotate {
    return YES;
}
@end
shouldAutorotateToInterfaceOrientation:はiOS 6では呼ばれないため、縦横位置に応じたレイアウト調整などをこのメソッドで行っていた場合はこのメソッドの代わりにwillRotateToInterfaceOrientation:duration:メソッドを利用することができます。このメソッドはiOS 5でも呼ばれるため、iOS 6のときだけ必要な処理を行うようにします。また、このようにすればiOS5、iOS6両方に対応可能になります。
実装例:
@implementation RotatableViewController
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    if ([self respondsToSelector:@selector(shouldAutorotate)]) {
        [self shouldAutorotateToInterfaceOrientation:toInterfaceOrientation];
    }
}
...
@end
http://scalper.posterous.com/ios-6-uinavigationcontrollerautorotate

このブログの人気の投稿

Belkin、コンパクトながら100W PD充電に対応した4ポートUSB-Cハブ「Connect USB-C to 4ポートUSB-Cハブ」を発売

温暖化で海面上昇するとどこが水没するか一発で分かる地図「Flood Maps」レビュー、未来の日本の海岸線はどうなっているのか?

ウェブサイトのユーザーを識別する「フィンガープリント」は考えられている以上にタチが悪いかもしれない