IOS横屏设置

1.全部禁止横屏

Targets->General->Deployment Info->Device Orientation

iOS开发禁止横屏.png

2.部分页面需要横屏,其他页面禁止横屏

需要勾选Targets->General->Deployment Info->Device Orientation->Landscape Left & Landscape Right


#pragma mark    注册一些通知,添加观察者 在APPDelegate中添加通知和以下方法,在需要横屏的界面允许横屏,需要勾选Targets->General->Deployment Info->Device Orientation->Landscape Left & Landscape Right

- (void)initializeTheNotificationCenter
{    
    //在进入需要全屏的界面里面发送允许横屏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startFullScreen) name:@"startFullScreen" object:nil];//允许横屏

    //在退出允许横屏的界面里面发送退出横屏的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endFullScreen) name:@"endFullScreen" object:nil];//退出横屏
}

#pragma mark 允许横屏
-(void)startFullScreen
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.allowRotation = YES;
}

#pragma mark    退出横屏
-(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];
    }
}

#pragma mark    禁止横屏
- (UIInterfaceOrientationMask )application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if (self.allowRotation) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

作者:肉身佛陀
链接:https://www.jianshu.com/p/5f5d46e674a7
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Leave a Comment