牛B的swift旋轉螢幕經驗終結者(OC統一思路),swiftoc
牛B的swift旋轉螢幕經驗終結者(OC統一思路)
1、AppDelegate
(1)定義變數 var blockRotation: Bool = false
(2)定義方法
Swift代碼
func application(application: UIApplication, supportedInterfaceOrientationsForWindow window: UIWindow?) -> UIInterfaceOrientationMask {
if self.blockRotation{
return UIInterfaceOrientationMask.All
} else {
return UIInterfaceOrientationMask.Portrait
}
}
2、要橫屏的viewController
(1)擷取變數
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
(2)在viewDidLoad中修改blockRotation變數值
override func viewDidLoad() {
super.viewDidLoad()
appDelegate.blockRotation = true
}
(3)viewWillAppear 設定頁面橫屏
override func viewWillAppear(animated: Bool) {
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
(4)viewWillDisappear設定頁面轉回豎屏
override func viewWillDisappear(animated: Bool) {
appDelegate.blockRotation = false
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
(5)橫屏頁面是否支援旋轉
// 是否支援自動橫屏。看項目可調,可以設定為true
override func shouldAutorotate() -> Bool {
return false
}
經驗總結:
上面情況是一個介面豎屏跳轉到第二個橫屏介面。
需要一個介面可以豎屏,然後想豎屏播放器那樣突然來個橫屏,怎麼辦,接下來就是放大招了:
給想要橫屏或者豎屏調用下面的動作。
// MARK: - 橫屏
func hengp() {
appDelegate.blockRotation = true
let value = UIInterfaceOrientation.LandscapeLeft.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
// MARK: - 豎屏
func shup() {
appDelegate.blockRotation = false
let value = UIInterfaceOrientation.Portrait.rawValue
UIDevice.currentDevice().setValue(value, forKey: "orientation")
}
// 將要發生旋轉就觸發代理
override func willRotateToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
}
// 旋轉完成觸發代理。我們需要在這裡對必要的介面設定重新布局
override func didRotateFromInterfaceOrientation(fromInterfaceOrientation: UIInterfaceOrientation) {
// 擷取當前手機物理狀態的螢幕模式,看看是橫屏還是豎屏.
let interfaceOrientation = UIApplication.sharedApplication().statusBarOrientation
if(interfaceOrientation == UIInterfaceOrientation.Portrait)
{
//當前是在豎屏模式
print("豎屏")
}else{
//當前是在橫屏模式
self.theWebView?.frame = self.view.frame
}
}
記住:橫屏後,和豎屏前的寬高度值是會變的,如果你有緩衝儲存了寬高度值,在這種情況下,橫屏後擷取到以前豎屏的儲存的寬高度值,一定要重新擷取,
let bWidth = CGRectGetWidth(UIScreen.mainScreen().bounds) ///< 螢幕寬度
let bHeight = CGRectGetHeight(UIScreen.mainScreen().bounds) ///< 螢幕高度