How to change the device orientation to portrait w

2019-04-17 01:09发布

问题:

Is there a possible way to autorotate the device orientation to portrait when the current orientation of the device is faceup or facedown?

回答1:

You can use this trick to make the system refresh your controller orientation anytime you want:

[self presentViewController:[UIViewController new] animated:NO completion:NULL];
[self dismissViewControllerAnimated:NO completion:NULL];

This will call supportedInterfaceOrientations on your controller.

Just return UIInterfaceOrientationMaskPortrait when the device orientation is facing up or down and your controller's view will get adjusted accordingly.


Observe UIDeviceOrientationDidChangeNotifications to use the trick when you receive the notification and it's a face up/down device orientation, as those orientation do not correspond to UIInterfaceOrientations (and won't trigger supportedInterfaceOrientations).

Device and interface orientation definitions:

typedef NS_ENUM(NSInteger, UIInterfaceOrientation) {
    UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,
    UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
    UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeRight,
    UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeLeft
};

typedef NS_ENUM(NSInteger, UIDeviceOrientation) {
    UIDeviceOrientationUnknown,
    UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom
    UIDeviceOrientationPortraitUpsideDown,  // Device oriented vertically, home button on the top
    UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
    UIDeviceOrientationLandscapeRight,      // Device oriented horizontally, home button on the left
    UIDeviceOrientationFaceUp,              // Device oriented flat, face up
    UIDeviceOrientationFaceDown             // Device oriented flat, face down
};


回答2:

You don't change the orientation. Instead, you tell iOS which orientations you support, so when the user rotates the device, iOS will switch the UI orientation to one that your application supports. The UI orientation should only change when the user rotates the device.



回答3:

Use this code in your - (void)viewWillApper method

if(self.interfaceOrientation==UIInterfaceOrientationPortrait||self.interfaceOrientation==UIInterfaceOrientationPortraitUpsideDown)
{
 //do something;
}
else
{
}


回答4:

You can disable or enable rotation of the screen in portrait mode by set an appropriate value in the project settings (Targets -> General -> Deployment Info section).

  • mark the Portrait checkbox
  • mark the Upside Down checkbox (this enable Upside Down animation)

or

  • mark the Portrait checkbox
  • unmark the Upside Down checkbox (this is only Upside mode)