为简单起见,对于 iPad,如果 info.plist 中的 Supported interface orientations (iPad) 属性包含所有四个方向,则 UIRequiresFullScreen 属性值为 NO ,iOS 会将您的应用视为支持拆分视图。如果一个应用程序支持拆分视图功能,你不能禁止它旋转,至少通过上述方式。
让我们深入了解细节。
首先,我们需要知道哪些因素会影响屏幕方向:
1.项目设置(info.plist)
有两个地方我们可以做这个设置:
-
项目->目标->常规->设备方向
-
项目的info.plist
这两种方法相同,一种会自动同步另一种设置。
在 info.plist 文件中,Supported interface orientations (iPad) 属性用于 iPad 设置(为 Device 部分选择 iPad),并且 支持的界面方向 属性适用于 iPhone 和 Universal(选择 iPhone 或 Universal 用于 Device 部分,这两个设置将始终为一样。)。
2。以编程方式设置支持的屏幕方向
有两种方法可以在编码时配置支持的方向:
-
supportedInterfaceOrientationsForWindow: 中的 UIApplicationDelegate 方法
-
supportedInterfaceOrientationsUIViewController 中的方法
iOS 系统会检查这两种方法中定义的共同方向,并将共同方向作为视图控制器支持的方向。
3.在UIViewController中设置shouldAutorotate属性
这是一个只读属性,用于控制视图控制器是否可旋转。您可以在视图控制器中覆盖该属性,甚至将该属性更改为读写属性,以便您可以在应用程序运行时修改该属性。例如:
override public var shouldAutorotate: Bool {
get {
return self.shouldAutorotateVariable
}
set {
self.shouldAutorotateVariable = newValue
}
}
shouldAutorotateVariable 是视图控制器中的私有属性。
iPhone
如果视图控制器的shouldAutorotate 属性设置为false,iOS 将省略以下设置:
-
supportedInterfaceOrientationsForWindow:UIApplicationDelegate 中的方法
-
supportedInterfaceOrientations 中的 UIViewController 方法
iOS 将仅使用项目设置 (info.plist)。
如果shouldAutorotate 属性未被覆盖或设置为true,则iOS 将使用以下两种方法中定义的常用方向:
-
supportedInterfaceOrientationsForWindow:UIApplicationDelegate 中的方法
-
supportedInterfaceOrientationsUIViewController 中的方法
如果没有提供以上两种方法,iOS 将使用项目设置(info.plist)。
iPad
从 iOS9 开始,iPad 支持拆分视图功能。分屏设置参考Slide Over and Split View Quick Start。
为简单起见,如果 info.plist 中的 Supported interface orientations (iPad) 属性包括所有四个方向,则 UIRequiresFullScreen 属性值为 NO,iOS 会将您的应用视为支持拆分视图。如果应用支持拆分视图,以下两项设置将被省略:
-
supportedInterfaceOrientationsForWindow:UIApplicationDelegate 中的方法
-
supportedInterfaceOrientations 中的 UIViewController 方法
UIViewController 中的 shouldAutorotate 属性也将被省略。
也就是说,如果一个应用程序支持拆分视图功能,你不能禁用它的旋转,至少通过上述方式。
如果 info.plist 值中的支持的界面方向 (iPad) 属性不包括所有四个方向,或者 UIRequiresFullScreen 属性设置为 YES em>,该应用将不支持分屏,屏幕方向控制逻辑与上面的iPhone相同。
注意:对于项目设置(info.plist),最好直接在info.plist里面设置以下三个属性:
- 支持的界面方向 (iPad)
- 支持的界面方向
- UIRequiresFullScreen
如果你尝试通过Project->Target->General->Device Orientation设置会很混乱:甚至Device被设置为Universe,iPad中的设置仍然会生效。