ios 横竖屏切换总结


  • UIViewController强制竖屏:

如果想整个APP竖屏,可以写一个BaseViewcontroller

1 先在AppDelegate.m里面重写如下方法

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window

{

 //返回你要支持的屏幕方向,如果只支持竖屏,直接返回竖屏的宏

}

2 在UIViewController的

- (void)viewWillAppear:(BOOL)animated{

//interfaceOrientation为方向宏定义

[[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:interfaceOrientation] forKey:@"orientation"];

}

  • 整体竖屏,但是个别界面需要横屏

如果界面中有个别界面需要横屏,可以增加一个标志位来控制supportedInterfaceOrientationsForWindow的返回值,比如:

- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window

{

    if (!self.allowRotation) {

        return UIInterfaceOrientationMaskPortrait;

    }

    return UIInterfaceOrientationMaskLandscapeRight; //界面只能往右旋转

}

然后在你需要横屏的UIViewController代码里面如下实现:(记得横屏标志位的值设置)

- (void) viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];

}

  • 兼容性问题

preferredInterfaceOrientationForPresentation这个方法在不同IOS版本的定义是不一样的。

<IOS9:

- (NSUInteger)preferredInterfaceOrientationForPresentation {

    return UIInterfaceOrientationPortrait;

}

>=IOS9

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {

    return UIInterfaceOrientationMaskPortrait;

}

注意如果重写了supportedInterfaceOrientations方法,那么在IOS7版本中从横屏切换到竖屏会存在切换不过来的问题。我当时就是在UIViewControler里面重写了

- (UIInterfaceOrientationMask)supportedInterfaceOrientations 

最后为了解决IOS7版本的问题,需要把如上重写删除。

同时注意UIViewController里面的interfaceOrientation属性也是在IOS8以后就不建议使用了。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM