How Do I detect the orientation of the device on iOS?

后端 未结 12 934
小鲜肉
小鲜肉 2020-11-30 01:56

I have a question on how to detect the device orientation on iOS. I don\'t need to receive change notifications, just the current orientation itself. This seems to be a rath

12条回答
  •  Happy的楠姐
    2020-11-30 02:47

    There's a way to achieve this whether the orientation lock is enabled or not by using data from CoreMotion. This is the code:

    #import  
    
        CMMotionManager *cm=[[CMMotionManager alloc] init];
        cm.deviceMotionUpdateInterval=0.2f;
        [cm startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                                withHandler:^(CMDeviceMotion *data, NSError *error) {
    
                                if(fabs(data.gravity.x)>fabs(data.gravity.y)){
                                        NSLog(@"LANSCAPE");
                                    if(data.gravity.x>=0){
                                        NSLog(@"LEFT");
                                    }
                                    else{
                                        NSLog(@"RIGHT");
                                    }
    
                            }
                            else{
                                    NSLog(@"PORTRAIT");
                                    if(data.gravity.y>=0){
                                        NSLog(@"DOWN");
                                    }
                                    else{
    
                                        NSLog(@"UP");
                                    }
    
                                }
    
    }];
    

提交回复
热议问题