swift 屏幕旋轉(zhuǎn)

豎直項目中遇到在某個頁面支持橫屏
第一步:
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

如果是進(jìn)來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")

如果是進(jìn)來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)的時候做處理 可以通過進(jìn)到UIViewController API 找到對應(yīng)時機的代理方法

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容