關于IOS中的屏幕部分旋轉

在做開發的時候經常碰到個別頁面需要橫屏的需求,比如播放視頻之類的。以前本人的習慣是把屏幕自動旋轉關掉,所以大部分時候都是Portrait狀態,除非使用一些視頻游戲應用的時候才會變成Landscape。當然也會有人是常年打開自動旋轉的,上次在測試一個app的時候,機主就是這樣的人,由于沒有注意這個問題導致有些界面因為橫豎切換的原因顯示混亂(當然這些東西完成可以用AutoLayout調好)其實這個問題很好解決,只要把下圖中LandscapeLeft和LandscapeRight的勾勾去掉即可。



可是問題來了如果遇到程序中需要部分旋轉的情況我們該如何處理呢?我們這里暫時不考慮用transform的情況,和大家交流一下shouldAutorotate的使用。用shouldAutorotate實現一個ViewController的旋轉需要在ViewController中實現下面三個方法:

    override func shouldAutorotate() -> Bool {
        return false
    }
    
    override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
        return .Portrait
    }

    override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
        return .Portrait
    }

一、關于shouldAutorotate文檔里有許多的詳細的描寫,由于英文一般簡單理解就是這個ViewController能不能旋轉,如果return值是false時這個ViewController不能旋轉反之則可以旋轉。
二、supportedInterfaceOrientations這個是此ViewController支持的方向有七種分別是:

public struct UIInterfaceOrientationMask : OptionSetType {
    public init(rawValue: UInt)
    
    public static var Portrait: UIInterfaceOrientationMask { get }
    public static var LandscapeLeft: UIInterfaceOrientationMask { get }
    public static var LandscapeRight: UIInterfaceOrientationMask { get }
    public static var PortraitUpsideDown: UIInterfaceOrientationMask { get }
    public static var Landscape: UIInterfaceOrientationMask { get }
    public static var All: UIInterfaceOrientationMask { get }
    public static var AllButUpsideDown: UIInterfaceOrientationMask { get }
}

這些方向均是Home鍵所在方向:
1.支持Home鍵朝下
2.支持Home鍵在左
3.支持Home鍵在右
4.支持Home鍵朝上
5.支持Home鍵在左右
6.支持所有方向
7.支持除Home鍵朝上以外的所有方向
如果此方法的返回值與 AppDelegate中supportedInterfaceOrientationsForWindow的返回值能夠對應的話,此ViewController會支持supportedInterfaceOrientations所返回的方向,也就是整個程序所支持的旋轉方向必須包含ViewController的支持方向。
三、preferredInterfaceOrientationForPresentation方法在文檔中是這樣解釋的:


preferredInterfaceOrientationForPresentation

當此ViewController支持多個方向的時候最優先顯示的屏幕方向。
注:preferredInterfaceOrientationForPresentation這個方法是我著重要說的,因為我在程序的開發中發現這個方法一直不執行,在網上也查了很多例子發現沒有說的很明白的,自己在測試中發現當頁面presentViewController的時候會執行,而常用的pushViewController時不會執行,原因應該是rootViewController的問題,也就是只有rootViewController才會執行presentViewController(如果這個地方有異議或者更好的解釋,可以請大家指出一起交流)。
由于上面preferredInterfaceOrientationForPresentation的問題在pushViewController的時候無法使我們的頁面橫屏,所以需要借助強制旋轉方法(參數是要旋轉的方向):

UIDevice.currentDevice().setValue(UIInterfaceOrientation.LandscapeLeft.rawValue, forKey: "orientation")

至此關于shouldAutorotate部分屏幕旋轉的內容就是這些了,附上demo地址https://github.com/Adverslty/RotationDome
demo里也有關于Statusbar在旋轉中的的顯示與隱藏。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容