判断“竖排锁定”是否打开

问题来由:

由于项目需要仅支持查看图片横竖屏转换,其他界面强制竖屏。因为转换过程中【状态栏】,【导航栏】需要隐藏显示等操作,【开启热点时状态栏】高度又从20变成40。界面在不断的跳转过程中加上热点的开闭,把手机搞“懵逼”了,一会界面上移,一会下移。

调整思路:

所有界面强制竖屏,由【陀螺仪】来判断设备的方向。陀螺仪和系统的横竖屏无关,此时就要获取设备是否开启“竖排锁定”,如果开启竖排锁定就禁用陀螺仪,如果关闭竖排锁定就启用陀螺仪。iOS 12以后获取“竖排锁定”的方法不准确,如下,再次又换了思路

//判断设备“竖屏锁定”的状态
inline BOOL isProtraitLockOn()
{
    BOOL isOn = NO;
    if([[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] isKindOfClass:NSClassFromString(@"UIStatusBar_Modern")]) {
        // iPhone X
        NSDictionary *barDic = [[[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"] valueForKeyPath:@"statusBar"]valueForKeyPath:@"_displayItemStates"];
        NSArray *values = [barDic allValues];
        NSLog(@"value = %@",values);//1️⃣
        for (id obj in values) {
            NSString *identifier = [[obj valueForKeyPath:@"identifier"] description];
            if ([identifier isEqualToString:@"_UIStatusBarIndicatorRotationLockItem"]) {
                NSString *flag =[[obj valueForKeyPath:@"dataEnabled"] description];
                if ([flag isEqualToString:@"1"]) {
                    NSLog(@"竖排方向锁定打开");
                    isOn = YES;

                }else{ //0
                    NSLog(@"竖排方向锁定关闭");
                    isOn = NO;
                }
                break;
            }
        }

    } else{
        id bar =[[UIApplication sharedApplication] valueForKeyPath:@"statusBar"];
        NSArray *array = [[bar valueForKeyPath:@"foregroundView"] subviews];
        //获取状态栏上的图标和状态,列入服务商,网络类型,时间,电池电量,蓝牙,等等
        NSLog(@"array = %@",array); //2️⃣
        for (id obj in array) {
            id item = [obj valueForKey:@"item"];
            int type = [[item valueForKey:@"type"] intValue];
            if (type == 18) { //18就是竖排锁定,ios 12以后不管“竖排锁定”打开与否。18都存在,所以本方法不准
                isOn = YES;
                break;
            }
        }
    }

    return isOn;
}

tip:可以查看1️⃣2️⃣两个打印,获取状态栏上其他元素,进行相应操作。

最终思路:

[[UIDevice currentDevice]beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientaionDidChange) name:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];

-(void)deviceOrientaionDidChange{
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;

    if (orientation == UIDeviceOrientationLandscapeLeft) {
      //横屏了
    }else if (orientation == UIDeviceOrientationLandscapeRight){
        //横屏
    }else{
       //其他都默认竖屏
    }
}


你可能感兴趣的:(判断“竖排锁定”是否打开)