iOS 強制螢幕轉向(force view orientation)
最近一個專案的需求,在整個專案裡的某一個View要強制轉成橫的,Google了好久,卡了1天才解決這個需求
1. 在Targets裡面要記得設定App支援的螢幕方向,Targets->Deployment Info->Device Orientation

收工!
1. 在Targets裡面要記得設定App支援的螢幕方向,Targets->Deployment Info->Device Orientation

2. 在要被強制轉向的View裡加入以下的code,做法就是進入viewDidLoad的時候把原本的螢幕方向記下來,然後轉成你要的方向,在viewWillDisappear的時候轉回來,override var shouldAutorotate, supportedInterfaceOrientations, preferredInterfaceOrientationForPresentation
//記錄原本的螢幕方向
var oldOrientation: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
//記下原本的螢幕方向
oldOrientation = UIDevice.current.orientation.rawValue
//強制landscapeRight
UIDevice.current.setValue(UIInterfaceOrientation.landscapeRight.rawValue, forKey: "orientation")
}
override var shouldAutorotate:Bool {
return false
}
override var supportedInterfaceOrientations:UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.landscapeRight
}
override var preferredInterfaceOrientationForPresentation:UIInterfaceOrientation {
return UIInterfaceOrientation.landscapeRight
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
//轉回來原來的方向
UIDevice.current.setValue(oldOrientation, forKey: "orientation")
}
收工!
留言
張貼留言