豎直項目中遇到在某個頁面支持橫屏
第一步:
AppDelegate中設(shè)置一個變量標(biāo)記是否要旋轉(zhuǎn)
var allowRotation = false
設(shè)置支持方向
func application(_ application: UIApplication, supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
if self.allowRotation {
return UIInterfaceOrientationMask.all
}
return UIInterfaceOrientationMask.portrait
}
第二步:
要支持的橫屏的vc
重寫shouldAutorotate方法
func shouldAutorotate() -> Bool {
return false
}
獲取appDelegate 用來修改是否旋轉(zhuǎn)變量
let appDeleagte = UIApplication.shared.delegate as! AppDelegate
如果是進來vc不需要支持旋轉(zhuǎn)特铝,點擊事件后才旋轉(zhuǎn)
在需要橫屏的事件中添加旋轉(zhuǎn)代碼
appDeleagte.allowRotation = true
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
在需要結(jié)束橫屏的事件中添加旋轉(zhuǎn)代碼
appDeleagte.allowRotation = false
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
如果是進來vc就需要支持旋轉(zhuǎn)則需要
override func viewDidLoad() {
appDeleagte.allowRotation = true
}
override func viewWillAppear(animated: Bool) {
let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
上面兩種場景在頁面消失的時候都要處理核畴,設(shè)置為豎屏
override func viewWillDisappear(animated: Bool) {
appDeleagte.allowRotation = false
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
}
如果需要旋轉(zhuǎn)的時候做處理 可以通過進到UIViewController API 找到對應(yīng)時機的代理方法