- 監聽設備旋轉方向 通過設備單例實現
設備方向是根據Home鍵確定的
必須先開始生成設備旋轉方向的通知 然后監聽通知 才可以處理設備的旋轉
//開啟設備方向通知
if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
//注冊通知
NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationChange(notification:)), name: .UIDeviceOrientationDidChange, object: nil)
func handleDeviceOrientationChange(notification:NSNotification) -> Void {
//獲取設備方向
//this will return UIDeviceOrientationUnknown unless device orientation notifications are being generated.
let currentOri = UIDevice.current.orientation
switch currentOri {
case .faceUp:
print("faceUp");
case .faceDown:
print("faceDown")
case .landscapeLeft:
print("landsapeLeft")
case .landscapeRight:
print("landscapeRight")
case .portrait:
print("portraint")
case .portraitUpsideDown:
print("portraintUpsideDown")
case .unknown:
print("unknown")
}
}
//移除通知
deinit {
//取消監聽
NotificationCenter.default.removeObserver(self)
//關閉設備方向通知
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
- 監聽屏幕旋轉方向,
如果要改變界面UI的話,大多情況這個更有用,因為如果設備發生旋轉,但屏幕并未旋轉就會出問題。
屏幕方向是根據狀態欄來判斷的
// 用戶界面方向是參考狀態欄方向的UIApplication.shared.statusBarOrientation
// 注冊通知
NotificationCenter.default.addObserver(self, selector: #selector(handleStatusBarOrientationChange(notification:)), name: NSNotification.Name.UIApplicationDidChangeStatusBarOrientation, object: nil)
}
func handleStatusBarOrientationChange(notification:NSNotification) -> Void {
let interfaceor = UIApplication.shared.statusBarOrientation
switch interfaceor {
case .portrait:
print("portrait")
case .portraitUpsideDown:
print("portraintUpsideDown")
case .landscapeLeft:
print("landsacpeLeft")
case .landscapeRight:
print("landscapeRight")
case .unknown:
print("unknown")
}
}
控制器中常用的控制界面方向的方法
// 是否支持旋轉
override var shouldAutorotate: Bool{
return true
}
// 屏幕支持的旋轉方向 UIInterfaceOrientation.portrait 表示僅支持豎直方向
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
return UIInterfaceOrientationMask.all
}
// 由模態推出的視圖控制器 優先支持的屏幕方向
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
return UIInterfaceOrientation.portrait
}