最近遇到視頻的需求鳖孤,里面有全屏岗憋,因此研究了一下全屏的問題实抡,
需求
- 進界面的時候是豎屏
- 進入 播放界面是豎屏
- 播放界面中可以自動翻轉(zhuǎn)
解決方案
其中糾結(jié)的部分就不提了欠母,直接說解決方案吧
需求1
需求1的重點在于欢策,讓app支持橫屏,但是進入界面的時候是豎屏
首先赏淌,通過設(shè)置TARGETS - General - Deployment info - Device orientation 的選項為第一個
25A3174B-677C-4531-B9E3-4C5BDC0EBC66.png
然后在AppDelegate中添加一下代理
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
//設(shè)置app支持的屏幕模式
return [.portrait, .landscapeLeft, .landscapeRight]
}
需求2
其實就是出了播放頁面外踩寇,所有頁面都是豎屏
viewController 有以下幾個屬性可供重寫,通過重寫這幾個方法六水,來實現(xiàn)界面的橫屏或豎屏
@available(iOS 6.0, *) //屏幕自動翻轉(zhuǎn)
open var shouldAutorotate: Bool { get }
@available(iOS 6.0, *) // 當前界面支持的屏幕方向
open var supportedInterfaceOrientations: UIInterfaceOrientationMask { get }
// Returns interface orientation masks.
@available(iOS 6.0, *) //初始屏幕方向俺孙,--但是實際上看意義不大
open var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { get }
經(jīng)過查坑發(fā)現(xiàn),VC里面重寫的方法并不是都能調(diào)用掷贾,因為被NavigationController和TabbarController給攔截了睛榄,需要在NavigationController和TabbarController中添加一下方法
如果沒有用到nav或者tab,就不用重寫了
-
ViewController中
override var shouldAutorotate: Bool { return true } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { return [.portrait, .landscapeRight, .landscapeLeft] } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { return .landscapeLeft }
-
NavigationController中
override var shouldAutorotate: Bool { if let top = topViewController { return top.shouldAutorotate } return false } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let top = topViewController { return top.supportedInterfaceOrientations } return .portrait } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { //測試著不怎么管用想帅,不知道為什么场靴, if let top = topViewController { return top.preferredInterfaceOrientationForPresentation } return .portrait }
-
TabbarController
open override var shouldAutorotate: Bool { if let vc = selectedViewController { return vc.shouldAutorotate } return false } open override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let vc = selectedViewController { return vc.supportedInterfaceOrientations } return .portrait }
通過重寫nav和tab里面的方法,調(diào)用VC里面重寫的方法港准。
需求3
其實上面就已經(jīng)實現(xiàn)了需求3的基本效果旨剥,如果再多說點,就是得加個屏幕翻轉(zhuǎn)的監(jiān)聽浅缸,來實現(xiàn)刷新界面之類的操作了--轨帜!廢話不多說,關(guān)門放代碼:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(onDeviceOrientationChange), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
func onDeviceOrientationChange() {
//界面方向發(fā)生變化
let orientation = UIDevice.current.orientation
let interfaceOrientation = UIInterfaceOrientation(rawValue: orientation.rawValue)
//該去做什么就去做什么吧
}