iOS开发禁止横屏

作者: 肉身佛陀 | 来源:发表于2016-09-17 16:52 被阅读6946次

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;
}

用来记录平时遇到的问题,不对之处还望斧正,如有更好的见解还望指教.

相关文章

网友评论

  • Vampire丶Lv:使用这种方法怎么进入不了全屏啊,发送通知了但allowRotation一直是NO。。
    肉身佛陀:不是全屏,是允许横屏,已修改;你看下demo,是你想要效果不,链接: https://pan.baidu.com/s/1o8t9nf0 密码: 66pe

本文标题:iOS开发禁止横屏

本文链接:https://www.haomeiwen.com/subject/ascwettx.html