supportedInterfaceOrientationsForが呼ばれない -Swift4

やりたいこと

アプリを初期起動した時、ipadだったらデバイスの向きをlandscapeLeftlandscapeRight限定の設定(ipadの向きを横画面のみ)にしてiPhoneならばportraitで縦画面のみ(iPhoneの向きを縦画面のみ)にしたいと思いました。

こんな感じに

if(デバイスがiPhoneなら){

   縦画面で固定

}else if(デバイスがiPad){

   横画面で固定

}

iPadの時だけ動かない

下記のように実装すれば、iPhoneの時は問題なく、動くのに、iPadの時は全然動きませんでした

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {

        var whatwhatDevice :  UIInterfaceOrientationMask = [.portrait]

        switch UIDevice.current.userInterfaceIdiom {

            case .phone:
                print("phone")
                 whatwhatDevice = [.portrait]
                  break

            case .pad:
                print("pad")
                 whatwhatDevice = [.landscapeLeft, .landscapeRight]]
                  break

        case .unspecified: break
        case .tv: break
        case .carPlay: break
        }
        return [whatwhatDevice]
    }

原因

原因はこれ。こんな風にinfo.plistに回転情報が書いてあると、xcodeはソースコードなんかよりも、info.plistの情報を優先するので、ipadの回転を制御しようとしても無駄です。

スクリーンショット 2017-12-11 14.15.43.png

完成した実装

info.plistに書かれているSupported interface orientations (iPad)情報を削除して下記のように実装しました。UIDevice.current.userInterfaceIdiomを使うとsupportedInterfaceOrientationsForでデバイスを判定しなかったのでUIDevice.current.modelでiPhoneかiPadかを判定しました

    func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {

        var whatwhatDevice :  UIInterfaceOrientationMask = [.landscapeLeft]

        if(UIDevice.current.model == "iPad"){
            whatwhatDevice  = [.landscapeLeft]

            print("pad")
        }

        if(UIDevice.current.model == "iPhone"){
            whatwhatDevice  = [.portrait]

            print("phone")
        }

        return [whatwhatDevice]
    }
藤沢瞭介(Ryosuke Hujisawa)
  • りょすけと申します。18歳からプログラミングをはじめ、今はフロントエンドでReactを書いたり、AIの勉強を頑張っています。off.tokyoでは、ハイテクやガジェット、それからプログラミングに関する情報まで、エンジニアに役立つ情報を日々発信しています!

未整理記事