牛B的swift屏幕旋轉經驗終結者(OC統一思路) 1、AppDelegate (1)定義變數 var blockRotation: Bool = false (2)定義方法 Swift代碼 func application(application: UIApplication, supported ...
牛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) ///< 屏幕高度