DeviceOrientation vs. ScreenSize vs StatusBar.isLandscape?
iOS 11、Swift 4 和 Xcode 9.X
无论是否使用 AutoLayout,有几种方法可以获得正确的设备方向,它们可用于在使用应用时检测旋转变化,以及在应用启动时或从后台恢复后获得正确的方向.
此解决方案在 iOS 11 和 Xcode 9.X 中运行良好
1. UIScreen.main.bounds.size:
如果您只想知道应用程序是处于横向还是纵向模式,则最好在启动时在viewDidLoad 中的rootViewController 中开始,如果您想检测旋转,则在rootViewController 中的viewWillTransition(toSize:)应用在后台时会发生变化,并且应该以正确的方向恢复 UI。
let size = UIScreen.main.bounds.size
if size.width < size.height {
print("Portrait: \(size.width) X \(size.height)")
} else {
print("Landscape: \(size.width) X \(size.height)")
}
这也发生在 app/viewController 生命周期的早期。
2。通知中心
如果您需要获取实际的设备方向(包括 faceDown、faceUp 等)。您想按如下方式添加观察者(即使您在AppDelegate 中的application:didFinishLaunchingWithOptions 方法中执行此操作,也可能会在执行viewDidLoad 后触发第一个通知
device = UIDevice.current
device?.beginGeneratingDeviceOrientationNotifications()
notificationCenter = NotificationCenter.default
notificationCenter?.addObserver(self, selector: #selector(deviceOrientationChanged),
name: Notification.Name("UIDeviceOrientationDidChangeNotification"),
object: nil)
并添加选择器如下。我将它分成两部分,以便能够在 viewWillTransition 中运行 inspectDeviceOrientation()
@objc func deviceOrientationChanged() {
print("Orientation changed")
inspectDeviceOrientation()
}
func inspectDeviceOrientation() {
let orientation = UIDevice.current.orientation
switch UIDevice.current.orientation {
case .portrait:
print("portrait")
case .landscapeLeft:
print("landscapeLeft")
case .landscapeRight:
print("landscapeRight")
case .portraitUpsideDown:
print("portraitUpsideDown")
case .faceUp:
print("faceUp")
case .faceDown:
print("faceDown")
default: // .unknown
print("unknown")
}
if orientation.isPortrait { print("isPortrait") }
if orientation.isLandscape { print("isLandscape") }
if orientation.isFlat { print("isFlat") }
}
请注意,UIDeviceOrientationDidChangeNotification 在发布期间可能会发布多次,在某些情况下可能是.unknown。我所看到的是,在viewDidLoad 和viewWillAppear 方法之后,以及在viewDidAppear 甚至applicationDidBecomeActive 之前收到了第一个正确的方向通知
方向对象将为您提供所有 7 种可能的场景(来自 enum UIDeviceOrientation 定义):
public enum UIDeviceOrientation : Int {
case unknown
case portrait // Device oriented vertically, home button on the bottom
case portraitUpsideDown // Device oriented vertically, home button on the top
case landscapeLeft // Device oriented horizontally, home button on the right
case landscapeRight // Device oriented horizontally, home button on the left
case faceUp // Device oriented flat, face up
case faceDown // Device oriented flat, face down
}
有趣的是,isPortrait 只读变量Bool 在UIDeviceOrientation 的扩展中定义如下:
extension UIDeviceOrientation {
public var isLandscape: Bool { get }
public var isPortrait: Bool { get }
public var isFlat: Bool { get }
public var isValidInterfaceOrientation: Bool { get }
}
3.状态栏方向
UIApplication.shared.statusBarOrientation.isLandscape
这也可以很好地确定方向是纵向还是横向,并给出与第 1 点相同的结果。您可以在 viewDidLoad(用于应用程序启动)和 viewWillTransition(toSize:)(如果来自背景)进行评估。但它不会为您提供您通过通知获得的上/下、左/右、上/下的详细信息(第 2 点)