一、前言
Swift版本 4.0
Xcode版本 9.2
以前接触到的项目需求中,几乎都是全竖屏展现界面,所以我也来得省事,直接在TARGETS中的界面方向选项中只勾选竖屏,这样就满足了需求。

但最近的项目中,产品突然增加了一个需求,需要部分界面支持旋转,这才来研究了一下屏幕旋转的问题!
需要紧急解决问题的道友直接看3.3
二、屏幕旋转相关知识
2.1 三个方向的理解和联系
UIDeviceOrientation: 设备方向
public enum UIDeviceOrientation : Int {
case unknown
case portrait // 设备vertically方向, home键在下方
case portraitUpsideDown // 设备vertically方向, home键在上方
case landscapeLeft // 设备horizontally方向, home键在右方
case landscapeRight // 设备horizontally方向, home键在左方
case faceUp // 设备flat方向, 屏幕朝上
case faceDown // 设备flat方向, 屏幕朝下
}
从设备方向的命名就能看出来这个枚举的含义,这里指的是物理设备(即iPhone)的方向。
UIInterfaceOrientation: 界面方向
public enum UIInterfaceOrientation : Int {
case unknown
case portrait
case portraitUpsideDown
case landscapeLeft
case landscapeRight
}
而界面方向指屏幕中显示内容的方向,它的方向和Home键的方向是一致的。仔细观察一下屏幕旋转就能理解UIDeviceOrientation和UIInterfaceOrientation了,我们把手机转向左边,可以看到界面随之才转向右边。
UIInterfaceOrientationMask: 是用来控制允许转向的方向,对应UIInterfaceOrientation
public struct UIInterfaceOrientationMask : OptionSet {
public init(rawValue: UInt)
public static var portrait: UIInterfaceOrientationMask { get }
public static var landscapeLeft: UIInterfaceOrientationMask { get }
public static var landscapeRight: UIInterfaceOrientationMask { get }
public static var portraitUpsideDown: UIInterfaceOrientationMask { get }
public static var landscape: UIInterfaceOrientationMask { get }
public static var all: UIInterfaceOrientationMask { get }
public static var allButUpsideDown: UIInterfaceOrientationMask { get }
}
2.2 观察屏幕旋转并作出响应
2.2.1 观察设备方向并响应
// 没有生成通知
if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
// 生成通知
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
// 锁定竖屏,依然有效,例如faceUp.
NotificationCenter.default.addObserver(self,
selector: #selector(handleDeviceOrientationChange(notification:)), name:NSNotification.Name.UIDeviceOrientationDidChange,
object: nil)










