web-dev-qa-db-ja.com

Swift-iPadでのみ回転を許可

Swiftで記述されたユニバーサルアプリで、iPhoneのポートレートモードのみをサポートし、iPadのポートレートモードとランドスケープモードの両方をサポートすることを許可するにはどうすればよいですか?

これまでAppDelegateで行われていたことは知っています。 Swiftでこれを行うにはどうすればよいですか?

37
felix_xiao

プログラムで行うこともできますが、プロジェクトのInfo.plistを編集することもできます(グローバルデバイス構成であるため、より実用的です)。

「サポートされているインターフェースの向き(iPad)」キーを追加するだけです

enter image description here

97
chrisamanse

プログラムでそれを行うことができます

override func shouldAutoRotate() -> Bool {
    if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
        return true
    }
    else {
        return false
    }
}

その後

override func supportedInterfaceOrientations() -> Int {
    return UIInterfaceOrientation.Portrait.rawValue
}

または、デフォルトで使用したいその他の回転方向。

これにより、使用しているデバイスがiPadであるかどうかが検出され、そのデバイスでのみ回転が許可されます。

編集:iPhoneでポートレートだけが必要なので、

 override func supportedInterfaceOrientations() -> Int {
    if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
        return UIInterfaceOrientation.Portrait.rawValue
    }
    else {
        return Int(UIInterfaceOrientationMask.All.rawValue)
    }
}
8
Kilenaitor

「サポートされているインターフェイスの向き(iPad)」キーをコピーして貼り付けるだけでChrisの答えが機能するかどうかはわかりません。おそらくinfo.plistのXMLソースからは判断できません。さまざまな向きのサポートを実現するため。 info.plist XMLソースを開いて、次のように編集できます。

<key>UISupportedInterfaceOrientations</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
</array>


<key>UISupportedInterfaceOrientations~ipad</key>
<array>
    <string>UIInterfaceOrientationPortrait</string>
    <string>UIInterfaceOrientationPortraitUpsideDown</string>
    <string>UIInterfaceOrientationLandscapeLeft</string>
    <string>UIInterfaceOrientationLandscapeRight</string>
</array> 

そして、xcode UIからイージーアプローチがあります。プロジェクト設定に移動します。 [全般]タブでターゲットを選択し、[導入情報]セクションで、まずiphone/ipadを選択し、各デバイスでサポートするデバイスの向きを個別にマークしてから、デバイスを[ユニバーサル]に変更します。フードの下で上記のxmlを生成します。 enter image description here

ここの「ユニバーサル」オプションは、iPhoneとiPadの間で共通の選択を示しています。

5
alizx

これまでAppDelegateで行われていたことは知っています。 Swiftでこれを行うにはどうすればよいですか?

使用する言語によってアプリケーションのアーキテクチャが変わることはありません。 Swiftでこれを行うには、Objective-Cで行う方法と同じです。つまり、次のように実装します。

optional func application(_ application: UIApplication,
         supportedInterfaceOrientationsForWindow window: UIWindow?) -> Int

アプリケーションデリゲートで。

2
Caleb

Swift 4:

override var supportedInterfaceOrientations:UIInterfaceOrientationMask {
    return UIDevice.current.userInterfaceIdiom == .pad ? UIInterfaceOrientationMask.all : UIInterfaceOrientationMask.portrait
}
0
Dion