Swift - 仅允许在 iPad 上旋转

问题描述 投票:0回答:6

如何让我在 iOS 8.3 SDK 上用 Swift 编写的通用应用程序仅支持 iPhone 上的纵向模式,但在 iPad 上支持纵向和横向模式?

我知道过去这是在 AppDelegate 中完成的。我怎样才能在 Swift 中做到这一点?

ios swift ipad
6个回答
142
投票

您可以通过编程方式完成此操作,或者更好的是,您可以简单地编辑项目的 Info.plist (这应该更实用,因为它是全局设备配置)

只需添加“支持的界面方向(iPad)”键

enter image description here


10
投票

您可以通过编程来完成

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)
    }
}

9
投票

我不确定克里斯的答案是否仅通过复制并粘贴“支持的界面方向(iPad)”键来起作用;可能不是从

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。

此处的“通用”选项显示了 iPhone 和 iPad 之间通用的选择。


2
投票

我知道过去这是在 AppDelegate 中完成的。我怎样才能在 Swift 中做到这一点?

您使用的语言不会改变应用程序的架构。在 Swift 中执行此操作的方式与在 Objective-C 中执行此操作的方式相同,即通过实现:

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

在您的应用程序委托中。


0
投票

如果您想在 Swift 4 中为特定 ViewController 设置此设置(在 iPad 上允许所有视图控制器,但在 iPhone 上仅允许纵向):

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

0
投票

Xcode 15 对于 iPhone 和 iPad 有单独的值

© www.soinside.com 2019 - 2024. All rights reserved.