在做開發(fā)的時(shí)候經(jīng)常碰到個(gè)別頁(yè)面需要橫屏的需求,比如播放視頻之類的。以前本人的習(xí)慣是把屏幕自動(dòng)旋轉(zhuǎn)關(guān)掉,所以大部分時(shí)候都是Portrait狀態(tài),除非使用一些視頻游戲應(yīng)用的時(shí)候才會(huì)變成Landscape。當(dāng)然也會(huì)有人是常年打開自動(dòng)旋轉(zhuǎn)的,上次在測(cè)試一個(gè)app的時(shí)候,機(jī)主就是這樣的人,由于沒有注意這個(gè)問題導(dǎo)致有些界面因?yàn)闄M豎切換的原因顯示混亂(當(dāng)然這些東西完成可以用AutoLayout調(diào)好)其實(shí)這個(gè)問題很好解決,只要把下圖中LandscapeLeft和LandscapeRight的勾勾去掉即可。
可是問題來(lái)了如果遇到程序中需要部分旋轉(zhuǎn)的情況我們?cè)撊绾翁幚砟兀课覀冞@里暫時(shí)不考慮用transform的情況,和大家交流一下shouldAutorotate的使用。用shouldAutorotate實(shí)現(xiàn)一個(gè)ViewController的旋轉(zhuǎn)需要在ViewController中實(shí)現(xiàn)下面三個(gè)方法:
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .Portrait
}
override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
return .Portrait
}
一、關(guān)于shouldAutorotate文檔里有許多的詳細(xì)的描寫,由于英文一般簡(jiǎn)單理解就是這個(gè)ViewController能不能旋轉(zhuǎn),如果return值是false時(shí)這個(gè)ViewController不能旋轉(zhuǎn)反之則可以旋轉(zhuǎn)。
二、supportedInterfaceOrientations這個(gè)是此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的返回值能夠?qū)?yīng)的話,此ViewController會(huì)支持supportedInterfaceOrientations所返回的方向,也就是整個(gè)程序所支持的旋轉(zhuǎn)方向必須包含ViewController的支持方向。
三、preferredInterfaceOrientationForPresentation方法在文檔中是這樣解釋的:
當(dāng)此ViewController支持多個(gè)方向的時(shí)候最優(yōu)先顯示的屏幕方向。
注:preferredInterfaceOrientationForPresentation這個(gè)方法是我著重要說(shuō)的,因?yàn)槲以诔绦虻拈_發(fā)中發(fā)現(xiàn)這個(gè)方法一直不執(zhí)行,在網(wǎng)上也查了很多例子發(fā)現(xiàn)沒有說(shuō)的很明白的,自己在測(cè)試中發(fā)現(xiàn)當(dāng)頁(yè)面presentViewController的時(shí)候會(huì)執(zhí)行,而常用的pushViewController時(shí)不會(huì)執(zhí)行,原因應(yīng)該是rootViewController的問題,也就是只有rootViewController才會(huì)執(zhí)行presentViewController(如果這個(gè)地方有異議或者更好的解釋,可以請(qǐng)大家指出一起交流)。
由于上面preferredInterfaceOrientationForPresentation的問題在pushViewController的時(shí)候無(wú)法使我們的頁(yè)面橫屏,所以需要借助強(qiáng)制旋轉(zhuǎn)方法(參數(shù)是要旋轉(zhuǎn)的方向):
UIDevice.currentDevice().setValue(UIInterfaceOrientation.LandscapeLeft.rawValue, forKey: "orientation")
至此關(guān)于shouldAutorotate部分屏幕旋轉(zhuǎn)的內(nèi)容就是這些了,附上demo地址https://github.com/Adverslty/RotationDome
demo里也有關(guān)于Statusbar在旋轉(zhuǎn)中的的顯示與隱藏。