美文网首页iOS技术
iOS:强制横屏的坑

iOS:强制横屏的坑

作者: 羊肉泡馍啊 | 来源:发表于2018-11-08 14:13 被阅读398次

    前段时间我们播放器强制横屏,项目设置允许竖屏,在手机不锁屏状态下,手机横屏会导致播放器强制横屏的时候会导致横屏失败,下面是强制横屏的解决办法以及我的探究.

    首先,在【General】-->【Device Orientation】设置仅支持竖屏


    image.png

    接下来在AppDelegate中设置

    在AppDelegate.h中添加是否允许横屏的标记
    
    /***  是否允许横屏的标记 */
    @property (nonatomic,assign)BOOL allowRotation;
    
    
    在AppDelegate.m中添加转屏的代理方法
    
    - (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    
        if (self.allowRotation) {
            return UIInterfaceOrientationMaskLandscapeRight;
        }
        return UIInterfaceOrientationMaskPortrait;
    }    
    

    先设置

    AppDelegate * appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.allowRotation = YES;
    

    接下来有两种办法可以在某个界面设置强制横屏
    第一种.先把设备状态设置为竖屏,再强制横屏

    //这句话是防止手动先把设备置为横屏[设备已经倾斜],导致下面的语句失效.
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationPortrait] forKey:@"orientation"];
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
    

    第二种.设置强制横屏,再调用

    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:UIInterfaceOrientationLandscapeRight] forKey:@"orientation"];
       //让屏幕方向与设备方向统一
    [UIViewController attemptRotationToDeviceOrientation];
    
    

    这样就解决手机不锁屏状态下的强制横屏导致的问题,但是为什么产生这些问题呢,请看下我接下来的探究.

    接下来说下横屏失败的原因:
    用户先向左转了设备的方向才点击横屏,在强制页面向右(也就是设备向左)横屏时,虽然项目是只允许竖屏的,屏幕界面方向也一直是竖屏的,但设备本身的方向(也就是[UIDevice currentDevice].orientation)其实已经是向左,此时其实kvc强制设置的值和本来的值是一样的,这就导致了屏幕界面不转动,所以可以先强制转到另一个方向再转回来,或者使用attemptRotationToDeviceOrientation方法使屏幕界面和设备方向同步。其他方向同理,另外,若用户启用了设备方向锁,用户无论如何旋转设备其设备方向都不变,也就不会有此问题。

    下面是我的思路:
    在屏幕没有锁定的时候,手机为横屏的时候,播放器横屏时候没有横屏

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

    但是播放器界面并没有变为全屏,根据效果我觉得有可能是宽高问题导致的,因此我先获取手机的屏幕方向

    [UIApplication sharedApplication].statusBarOrientation
    

    在获取手机的设备方向

    [UIDevice currentDevice].orientation
    

    发现屏幕方向和设备方向不一致


    image.png

    接下来使屏幕方向和设备方向一致,就可以解决问题

    参考文章
    iOS 获取屏幕方向

    相关文章

      网友评论

        本文标题:iOS:强制横屏的坑

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