- 監(jiān)聽設(shè)備旋轉(zhuǎn)方向 通過設(shè)備單例實(shí)現(xiàn)
設(shè)備方向是根據(jù)Home鍵確定的
必須先開始生成設(shè)備旋轉(zhuǎn)方向的通知 然后監(jiān)聽通知 才可以處理設(shè)備的旋轉(zhuǎn)
//開啟設(shè)備方向通知
if !UIDevice.current.isGeneratingDeviceOrientationNotifications {
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
}
//注冊(cè)通知
NotificationCenter.default.addObserver(self, selector: #selector(handleDeviceOrientationChange(notification:)), name: .UIDeviceOrientationDidChange, object: nil)
func handleDeviceOrientationChange(notification:NSNotification) -> Void {
//獲取設(shè)備方向
//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 {
//取消監(jiān)聽
NotificationCenter.default.removeObserver(self)
//關(guān)閉設(shè)備方向通知
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
- 監(jiān)聽屏幕旋轉(zhuǎn)方向,
如果要改變界面UI的話,大多情況這個(gè)更有用,因?yàn)槿绻O(shè)備發(fā)生旋轉(zhuǎn),但屏幕并未旋轉(zhuǎn)就會(huì)出問題。
屏幕方向是根據(jù)狀態(tài)欄來判斷的
// 用戶界面方向是參考狀態(tài)欄方向的UIApplication.shared.statusBarOrientation
// 注冊(cè)通知
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")
}
}
控制器中常用的控制界面方向的方法
// 是否支持旋轉(zhuǎn)
override var shouldAutorotate: Bool{
return true
}
// 屏幕支持的旋轉(zhuǎn)方向 UIInterfaceOrientation.portrait 表示僅支持豎直方向
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
return UIInterfaceOrientationMask.all
}
// 由模態(tài)推出的視圖控制器 優(yōu)先支持的屏幕方向
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
return UIInterfaceOrientation.portrait
}