场景一:
最近项目中加了视频播放,视频播放的话,肯定会涉及到全屏播放,全屏和小屏好做,主要是旋转.
发现下面方法不调用:
- (BOOL)shouldAutorotate
{
return NO;
}
说明:
1.如果只有ViewController的话,shouldAutorotate,一定会走的.
2.但是关键是我们项目都是navigationController,shouldAutorotate方法就不会走了.属于方法被navigationController拦截了.这样就需要在你的navigationController基类添加以下代码:-(BOOL)shouldAutorotate{
return self.topViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
returnUIInterfaceOrientationLandscapeRight;
}
3.但是我发现ViewController里的shouldAutorotate还是不执行,我分析了一下,还是被拦截了,原因是我们项目都有tabbarController,也会被这个拦截掉.所以在你的tabbarController的基类里边添加如下代码:
- (BOOL)shouldAutorotate{
return self.selectedViewController.shouldAutorotate;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
return UIInterfaceOrientationLandscapeRight;
}
4.最后别忘记在你的ViewController里边添加这个代码:
- (BOOL)shouldAutorotate{
return NO;
}
场景二:
程序只有一个简单的ViewController,要求启动后只横版显示,不能旋转。我设置了一下Info.plist中的支持方向后,在ViewController.m中加入如下代码:
- (BOOL)shouldAutorotate { return NO;}
结果shouldAutorotate不调用,程序该旋转还是旋转。
解决
这种问题一般出在粗心,或者是iOS 9的分屏应用中。我的问题在于没有针对设备设置好Info.plist。只限制了Universal的方向,在iPad设备中却允许所有方向。
可以采用以下两种方式之一解决:
正确设置设备的允许方向: 在TARGETS -> General -> Deployment Info 将 Devices 设置为iPad, 再将 Device Orientation下勾选 Landscape Left 和 Landscape Right。
我先前在Devices设置为Universal时限制了方向,而Devices为iPad时,每个方向都是被勾选的。这个时候就允许了所有方向,shouldAutorotate函数在没有禁止分屏的情况下是不会被调用的。
设置全屏显示(禁止分屏): 在TARGETS -> General -> Deployment Info 将 Requires full screen 勾选。
苹果论坛中说,当开发分屏应用时也就放弃了对屏幕旋转的控制。这里虽然不是分屏应用,但显性要求全屏显示,可以让就算在支持所有方向的情况下,shouldAutorotate函数也会被调用。
场景三:有的项目当中你仅仅想在某个页面支持横竖屏但在其他页面只需要竖屏
步骤1:在info.plist中添加项目中所有要支持的方向(比如:我在项目中只有视频播放模块使用竖屏Portrait,left,right),那么也要正确设置设备的允许方向: 在TARGETS -> General -> Deployment Info 将 Device Orientation下勾选 Portrait Landscape Left 和 Landscape Right。在info.plist做也行.
步骤2.写个category 设置其他类除了竖屏都不支持如下:
@implementation UIViewController (JFPlayerRotation)
/**
* 默认所有都不支持转屏,如需个别页面支持除竖屏外的其他方向,请在viewController重新下边这三个方法
*/
// 是否支持自动转屏
- (BOOL)shouldAutorotate
{
return YES;
}
// 支持哪些屏幕方向
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}
// 默认的屏幕方向(当前ViewController必须是通过模态出来的UIViewController(模态带导航的无效)方式展现出来的,才会调用这个方法)
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
return UIInterfaceOrientationPortrait;
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (BOOL)shouldAutorotate
{
return YES;
}
备注:shouldAutorotate设置为yes
- (UIInterfaceOrientationMask)supportedInterfaceOrientations才有效