美文网首页
iOS全局禁止横屏,特定页面全屏解决方法

iOS全局禁止横屏,特定页面全屏解决方法

作者: 老刘了 | 来源:发表于2019-12-17 11:16 被阅读0次

    # 1. 全局禁止横屏

    在Appdelegate.h添加以下属性:

    /***  是否允许横屏的标记 */
    @property (nonatomic,assign)BOOL allowRotation;
    

    Appdelegate.m添加如下代码:

    -(UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
        if (self.allowRotation) {//如果设置了allowRotation属性,支持全屏
            return UIInterfaceOrientationMaskAll;
        }
        return UIInterfaceOrientationMaskPortrait;//默认全局不支持横屏
    }
    

    2. 在需要支持横屏的界面改变allowRotation属性

    //进入全屏
    -(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];
        }
    }
    

    在viewWillAppear和viewWillDisappear分别调用以上方法,在该控制器下即可顺利支持全屏。

    - (void)viewWillAppear:(BOOL)animated {
    
        [super viewWillAppear:animated];
        [self begainFullScreen];
    }
    
    - (void)viewWillDisappear:(BOOL)animated {
    
        [super viewWillDisappear:animated];
        [self endFullScreen];
    }
    

    相关文章

      网友评论

          本文标题:iOS全局禁止横屏,特定页面全屏解决方法

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