Swift中獲取手機屏幕方向,和Object-C中類似。屏幕方向改變時,系統會發出通知,我們只要在 ViewController 里注冊屏幕方向改變的通知即可。
1.注冊通知
//注冊手機屏幕方向切換的通知
NotificationCenter.default.addObserver(self,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? selector:#selector(ViewController.orientationChanged(_:)),
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?name:NSNotification.Name.UIDeviceOrientationDidChange,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? object:nil)
2.通知實現方法
funcorientationChanged(_notification:NSNotification) {
? ?//獲得當前運行中設備信息
? ?letdevice =UIDevice.current
? ?//遍歷設備屏幕方向
? ?switchdevice.orientation{
? ?case.portrait:
? ? ? ?print("設備屏幕位于垂直方面,Home鍵位于下方")
? ?case.portraitUpsideDown:
? ? ? ? print("設備屏幕位于垂直方面,Home鍵位于上方")
? ?case.landscapeLeft:
? ? ? ?print("設備屏幕位于水平方面,Home鍵位于右側")
? ?case.landscapeRight:
? ? ? print("設備屏幕位于水平方面,Home鍵位于左側")
? ?case.faceUp:
? ? ? ?print("設備處于平放,Home鍵朝上")
? ?case.faceDown:
? ? ? ?print("設備處于平放,Home鍵朝下")
? ?case.unknown:
? ? ? ?print("設備屏幕方向未知")
? ?}
}