关于IOS中的屏幕部分旋转

在做开发的时候经常碰到个别页面需要横屏的需求,比如播放视频之类的。以前本人的习惯是把屏幕自动旋转关掉,所以大部分时候都是Portrait状态,除非使用一些视频游戏应用的时候才会变成Landscape。当然也会有人是常年打开自动旋转的,上次在测试一个app的时候,机主就是这样的人,由于没有注意这个问题导致有些界面因为横竖切换的原因显示混乱(当然这些东西完成可以用AutoLayout调好)其实这个问题很好解决,只要把下图中LandscapeLeft和LandscapeRight的勾勾去掉即可。

关于IOS中的屏幕部分旋转
文章图片

可是问题来了如果遇到程序中需要部分旋转的情况我们该如何处理呢?我们这里暂时不考虑用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方法在文档中是这样解释的:

关于IOS中的屏幕部分旋转
文章图片
preferredInterfaceOrientationForPresentation
当此ViewController支持多个方向的时候最优先显示的屏幕方向。
注:preferredInterfaceOrientationForPresentation这个方法是我着重要说的,因为我在程序的开发中发现这个方法一直不执行,在网上也查了很多例子发现没有说的很明白的,自己在测试中发现当页面presentViewController的时候会执行,而常用的pushViewController时不会执行,原因应该是rootViewController的问题,也就是只有rootViewController才会执行presentViewController(如果这个地方有异议或者更好的解释,可以请大家指出一起交流)。
由于上面preferredInterfaceOrientationForPresentation的问题在pushViewController的时候无法使我们的页面横屏,所以需要借助强制旋转方法(参数是要旋转的方向):
UIDevice.currentDevice().setValue(UIInterfaceOrientation.LandscapeLeft.rawValue, forKey: "orientation")

【关于IOS中的屏幕部分旋转】至此关于shouldAutorotate部分屏幕旋转的内容就是这些了,附上demo地址https://github.com/Adverslty/RotationDome
demo里也有关于Statusbar在旋转中的的显示与隐藏。

    推荐阅读