iOS项目中横竖屏切换

作者: 乔兰伊雪 | 来源:发表于2018-05-29 13:31 被阅读21次

    项目里面页面整体竖屏,但是有横屏情况就需要在general中将device orientation的几个方向都选上,如果只选了竖屏是没办法在项目里通过代码支持横屏的。

    一般项目里都会有UINavigationController,写一个UINavigationController的子类,实现下面方法,如果项目里有下导航,则在UITabBarController里也实现此方法:

    #if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_9_0
    - (NSUInteger)supportedInterfaceOrientations
    #else
    - (UIInterfaceOrientationMask)supportedInterfaceOrientations
    #endif
    {
        return UIInterfaceOrientationMaskPortrait;//设置只要是导航控制器就是竖屏  
    }
    

    在需要用到导航控制器的时候所创建的导航都继承这个子类,就能保证所有的页面都是竖屏,想要横屏的时候选择present一个vc,在vc中实现下述代码:

    //支持旋转
    -(BOOL)shouldAutorotate{
             return YES;
    }
    
     //支持的方向 
    - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
             return UIInterfaceOrientationMaskLandscapeRight;
     }
    -(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
             return UIInterfaceOrientationLandscapeRight;
    }
    -(void)viewWillAppear:(BOOL)animated{
    
    }
    

    这样present的这个vc就可以旋转横屏了

    如果想自己控制每个页面的横竖屏,就需要在UINavigationController的子类这样写:

    -(BOOL)shouldAutorotate{
        return self.topViewController.shouldAutorotate;
    }
    //支持的方向
    - (UIInterfaceOrientationMask)supportedInterfaceOrientations {
        return self.topViewController.supportedInterfaceOrientations;
    }
    

    然后在具体的vc中设置vc的方向即可。
    参照:iOS设置某个界面强制横屏,进入就横屏

    相关文章

      网友评论

        本文标题:iOS项目中横竖屏切换

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