LoginSignup
57
57

More than 5 years have passed since last update.

iOS6以上とiOS5の自動回転の制御について

Last updated at Posted at 2013-02-11

まずiOS SDK6自体の回転に関する前提

・iOS6以上とiOS5では自動回転のメソッドが違う
・iOS SDK6から以前の回転のメソッドが非推奨になった
・iOS SDKが6以上であっても実行する端末がiOS5に対応するのであればiOS5向けの実装をしないといけない

最初に結論

・iOS6の場合、コンテナを使いそれぞれのViewControllerで回転の可否を決めたい場合は工夫が必要

iOS SDK6からの自動回転

iOS6からの自動回転についてはUIViewControllerのshouldAutorotateメソッドで、そのViewControllerで回転処理が存在するかどうかをBOOLで返し、回転する方向をsupportedInterfaceOrientationsメソッドで指定する。

iOS6のUIViewController自動回転メソッド
//回転処理が存在するかどうかを返す
- (BOOL)shouldAutorotate
{
    return NO;
}

//回転する方向を指定
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}

コンテナを使っている場合は子供の指定にまかせる

UITabBarControllerやUINavigationControllerなどのようなコンテナを使っていて、そのコンテナに追加している子ViewControllerで回転したい方向をそれぞれで指定したい場合、それぞれの子ViewControllerで処理を任せるようにするのがよさそう。

つまり、コンテナ自体のshouldAutorotateメソッド、supportedInterfaceOrientationsメソッドが呼び出された際、コンテナに追加された子ViewControllerのそれらのメソッドを呼び出すようにする。

具体的には、まずUITabBarControllerを使っている場合、タブで選択されたViewControllerのshouldAutorotateメソッド、supportedInterfaceOrientationsで回転処理の方向を指定させるようにする。

UITabBarControllerには選択されたタブを取得するselectedViewControllerプロパティがあるため、次のようにできる。

UITabBarControllerを継承して実装
//回転させるかどうか
- (BOOL)shouldAutorotate
{
    //タブで選択されたViewController(navigationならnavigation)に任せる
    return [self.selectedViewController shouldAutorotate];
}

//回転させる向きを指定
- (NSUInteger)supportedInterfaceOrientations
{
    //選択したViewController(navigationならnavigation)に任せる
    return [self.selectedViewController supportedInterfaceOrientations];
}

UINavigationControllerには表示されているViewControllerを取得するvisibleViewControllerがあるため、次のようにできる。

UINavigationControllerを継承して実装
- (BOOL)shouldAutorotate
{
    //表示しているViewControllerにまかせる
    return [self.visibleViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations
{
   //表示しているViewControllerにまかせる
   return [self.visibleViewController supportedInterfaceOrientations];
}

iOS5の自動回転

iOS5の自動回転についてはUIViewControllerのshouldAutorotateToInterfaceOrientation:メソッドを利用する。

iOS5のUIViewController自動回転メソッド
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
     //interfaceOriaentationで識別子回転する方向であればYESを返す
     return YES;
}

iOS6と違い、UITabBarControllerやUINavigationControllerを使っている場合も意識する必要がなく、回転させたいViewController上でshouldAutorotateToInterfaceOrientation:メソッドを実行すれば良い。

ソースコード

githubに置いてます
https://github.com/yimajo/AutoRotateDemo

突っ込みどころ等あれば編集リクエストなり、コメントなりgit hubのpull requestなりでお願いします。

参考

57
57
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
57
57