Detect iOS device orientation lock

前端 未结 3 673
青春惊慌失措
青春惊慌失措 2020-12-30 09:59

How can I programmatically check whether the device orientation is locked in iOS? I see nothing in UIDevice. I know that this is supposed to be transparent to the app. But I

相关标签:
3条回答
  • 2020-12-30 10:22

    I don't think you can find out if the orientation is locked. I have looked for that some time ago and found nothing. What you can do is ignoring the orientation and just offer landscape in your view controller... then it will be shown in landscape no matter what.

    I think this is what youtube is doing as well.

    0 讨论(0)
  • 2020-12-30 10:25

    You can use the UIAccelerometer class to determine the phone's orientation in great detail. If the acceleration vector enters a state where its largest absolute component is on the X axis, that is a landscape orientation. In theory this could be used to detect the orientation lock: if, within a few seconds of this happening, the controller does NOT receive a call to shouldRotateToInterfaceOrientation, and the [[UIDevice currentDevice] orientation] property is not in landscape, you could then safely assume the user has the orientation locked.

    This complicated, and has a delay because shouldRotateToInterfaceOrientation will be called well after the actual vector has actually entered a landscape region. The whole idea is a bit of a hack, and you should probably reconsider why you really need to present landscape views when the user has a preference not to show them.

    0 讨论(0)
  • 2020-12-30 10:45

    There's no way how to detect if orientation is locked or not. YouTube app doesn't lock to landscape, it just displays movie in landscape orientation, but when you rotate your iPhone, movie rotates as well (if there's no orientation lock).

    IOW orientation lock is handled by system, transparent to your application.

    If you want to achieve this functionality - just display your view in landscape mode even if the iPhone is in portrait mode and later enable rotation of your view. It will behave in the same way as YouTube app.

    Update for comment:

    .h
    
    BOOL rotationEnabled;
    
    .m
    
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
      return rotationEnabled || ( toInterfaceOrientation == UIInterfaceOrientationLandscapeRight );
    }
    
    - (void)viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
      rotationEnabled = YES;
    }
    
    0 讨论(0)
提交回复
热议问题