为了实现这个功能,网上看了几篇文章,发现基本都是一样,
第一步就是在 Appdelegate 里面进行如下操作:
-(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
if (self.allowRotation) {//如果设置了allowRotation属性,支持横屏
return UIInterfaceOrientationMaskLandscapeRight;
}
return UIInterfaceOrientationMaskPortrait;//默认全局不支持横屏
}
第二步就是在需要横屏的页面写上已下代码
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self begainFullScreen];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self endFullScreen];
}
//进入全屏
-(void)begainFullScreen
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = YES;
}
// 退出全屏
-(void)endFullScreen
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.allowRotation = NO;
// //强制归正:
if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
SEL selector = NSSelectorFromString(@"setOrientation:");
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
[invocation setSelector:selector];
[invocation setTarget:[UIDevice currentDevice]];
int val =UIInterfaceOrientationPortrait;
[invocation setArgument:&val atIndex:2];
[invocation invoke];
}
}
本以为这样就大功告成,没想到在运行的时候崩溃了,崩溃信息如下:
'UIApplicationInvalidInterfaceOrientation', reason: 'Supported orientations has no common orientation with the application, and [ZDFullScreenController shouldAutorotate] is returning YES'
最后发现造成这个崩溃的原因是- (BOOL)shouldAutorotate这个方法系统默认的YES,改成NO就可以了。