牛B的swift屏幕旋轉經驗終結者(OC統一思路)


牛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///<    屏幕高度

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM