supportedInterfaceOrientationsForが呼ばれない -Swift4
やりたいこと
アプリを初期起動した時、ipadだったらデバイスの向きをlandscapeLeft
とlandscapeRight
限定の設定(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の回転を制御しようとしても無駄です。
完成した実装
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]
}