iOS设置某个VC只能横屏,其他VC只能竖屏

2019-4-10

效果:

屏幕旋转.gif

一、targets选择
image.png

二、根控制器(UINavigationController 或 UITabBarController)重写

- (BOOL)shouldAutorotate {
    return YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    //判断当前顶层显示的是 你要设置横屏的那个控制器(FireAnimationViewController)
    if([self.selectedViewController isKindOfClass:[UINavigationController class]] && [[(UINavigationController *)[self selectedViewController] topViewController] isKindOfClass:[FireAnimationViewController class]]){
        return UIInterfaceOrientationMaskLandscape;
    }
    else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationPortrait;
}

三、在要设置横屏的VC里设置

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
     //首先设置UIInterfaceOrientationUnknown欺骗系统,避免可能出现  直接设置无效的情况
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationUnknown] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
}
-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    //首先设置UIInterfaceOrientationUnknown欺骗系统,避免可能出现直接设置无效的情况
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationUnknown] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInt:UIInterfaceOrientationPortrait] forKey:@"orientation"];

}

重写view的出现和消失方法 改变设备的方向,主要触发根控制器的supportedInterfaceOrientations方法 使屏幕旋转,如果不设置,会发现push进来时VC没旋转,手动旋转屏幕VC才会改变方向,view消失时同理,不设置则会pop出来的时候,vc和上个页面一样是横屏的,手动旋转屏幕才会变成竖屏的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容