您的位置:首页 > 移动开发 > IOS开发

iOS横屏竖屏旋转的方法(怕留网址会消失,直接复制内容过来了)

2014-12-11 16:44 399 查看
NSFish 285 11月28日
回答 · 11月28日 更新

以下方法仅对deploy target大于等于iOS6的工程有效,如果题主的应用需要支持iOS5(默哀),请pass。

在info.plist中设置方向,包含你需要的所有方向,以题中意,UpSideDown和LandScapeLeft;
继承UITabBarController,override以下三个方法

- (BOOL)shouldAutorotate
{
return [self.selectedViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations
{
return [self.selectedViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.selectedViewController preferredInterfaceOrientationForPresentation];
}


继承UINavigationController,override和UITabBarController中相同的方法,将selectedViewController改为topViewController

- (BOOL)shouldAutorotate
{
return [self.topViewController shouldAutorotate];
}

- (NSUInteger)supportedInterfaceOrientations
{
return [self.topViewController supportedInterfaceOrientations];
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return [self.topViewController preferredInterfaceOrientationForPresentation];
}


在真正实现界面的ViewController里,override上面这三个方法,override规则如下:

preferredInterfaceOrientationForPresentation表示viewController初始显示时的方向;

supportedInterfaceOrientations是在该viewController中支持的所有方向;

shouldAutorotate表示是否允许旋屏。

流程说明

首先,对于任意一个viewController,iOS会以info.plist中的设置和当前viewController的preferredInterfaceOrientationForPresentation和supportedInterfaceOrientations三者支持的方法做一个交运算,若交集不为空,则以preferredInterfaceOrientationForPresentation为初始方向,交集中的所有方向均支持,但仅在shouldAutorotate返回YES时,允许从初始方向旋转至其他方向。若交集为空,进入viewController时即crash,错误信息中会提示交集为空。

其次,UINavigationController稍有些特别,难以用常规API做到同一个naviVC中的ViewController在不同方向间自如地切换。(如果去SO之类的地方搜索,会找到一个present empty viewController and then dismiss it之类的hacky trick,不太建议使用),如果要在横竖屏间切换,建议使用presentXXX方法。

再次,AppDelegate中有一个委托方法可以动态的设置应用支持的旋转方向,且此委托的返回值会覆盖info.plist中的固定设置。使用该方法的便利之处不言自明,但缺点是搞明白当前哪个ViewController即将要被显示,很可能会导致耦合增加;

最后,以上均为个人在iOS8 SDK下得到的实践结果,请题主结合工程实际参考使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: