如何手动设置设备方向时,App部署信息画像锁定



我不希望我的应用程序景观,总是肖像。所以我让我的应用程序部署信息只设置肖像。但是当我需要在我的应用程序中显示任何图像或视频时,我需要横向模式以更好地显示。

我可以通过

检测设备方向的变化
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(orientationChanged:)
 name:UIDeviceOrientationDidChangeNotification
 object:[UIDevice currentDevice]];
- (void) orientationChanged:(NSNotification *)note
{
UIDevice * device = note.object;
switch(device.orientation)
{
    case UIDeviceOrientationPortrait:
        /*  */
        break;
    case UIDeviceOrientationPortraitUpsideDown:
        /*  */
        break;
    case UIDeviceOrientationLandscapeLeft:
       /*  */
       break;
    case UIDeviceOrientationLandscapeRight:
       /*  */
       break;
    default:
        break;
};
}

但是我如何手动更改我的设备方向,即使应用程序部署信息肖像被锁定?

这个不工作

NSNumber *value=[NSNumber numberWithInt: UIDeviceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"]; 

请启用竖屏&项目设置中的横向。然后使用下面的方法为所有的视图控制器自动旋转关闭-

- (BOOL)shouldAutorotate {
    return NO;
}

然后使用下面的方法所有除了景观视图控制器-

- (void)viewWillAppear:(BOOL)animated {
    [[UIDevice currentDevice] setValue:
     [NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
                                forKey:@"orientation"];
}

使用下面的方法为景观视图控制器-

- (void)viewWillAppear:(BOOL)animated {
        [[UIDevice currentDevice] setValue:
         [NSNumber numberWithInteger: UIInterfaceOrientationLandscapeLeft]
                                    forKey:@"orientation"];
    }

如果你正在使用NavigationController和TabBarController,那么请使用category来关闭自动旋转。

两步:

  1. 包括横向部署
  2. 在每个视图控制器viewDidLoad中,您需要包括:

    //Swift
    let value = UIInterfaceOrientation.LandscapeLeft.rawValue
    UIDevice.currentDevice().setValue(value, forKey: "orientation")
    //Obj-C
    NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
    [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
    

参见:如何在iOS7中以编程方式设置设备方向?

你应该创建一个横向导航控制器的子类,并通过呈现来使用它,而不是强制改变方向。然后你的应用就会一直是你想要的竖屏。当你使用这个导航控制器时,它会横屏。

#import "RotationAwareNavigationController.h"
@implementation RotationAwareNavigationController
-(BOOL)shouldAutorotate {
    return NO;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeRight;
}
- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

你应该像下面这样调用它;

RotationAwareNavigationController *navController = [[RotationAwareNavigationController alloc] initWithRootViewController:aViewController];
[self presentViewController:navController animated:NO completion:nil];

Swift 3+的更新答案:

let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")

最新更新