5

我不希望我的应用程序被美化并且始终是纵向的。所以我将我的应用程序部署信息设置为仅设置纵向。但是当我需要在我的应用中显示任何图像或视频时,我需要横向模式才能更好地显示。

我可以通过以下方式检测设备方向变化

[[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"]; 
4

4 回答 4

8

请从您的项目设置中启用纵向和横向。然后使用以下方法让所有视图控制器自动关闭 -

- (BOOL)shouldAutorotate {
    return NO;
}

然后对除 LandScapeViewControler 之外的所有方法使用以下方法 -

- (void)viewWillAppear:(BOOL)animated {

    [[UIDevice currentDevice] setValue:
     [NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
                                forKey:@"orientation"];
}

对 LandScapeViewControler 使用以下方法 -

- (void)viewWillAppear:(BOOL)animated {

        [[UIDevice currentDevice] setValue:
         [NSNumber numberWithInteger: UIInterfaceOrientationLandscapeLeft]
                                    forKey:@"orientation"];
    }

如果您使用 NavigationController 和 TabBarController ,请使用 category 关闭自动旋转。

希望这会对您有所帮助。

于 2015-05-21T09:32:57.300 回答
6

两步:

  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 中以编程方式设置设备方向?

于 2015-05-21T09:17:53.540 回答
3

而不是强制改变方向,您应该子类化一个横向的导航控制器并通过呈现来使用它。然后,您的应用程序将始终是您想要的肖像。当您使用此导航控制器时,它将横向显示。

#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];
于 2015-05-21T09:21:57.920 回答
0

Swift 3+ 的更新答案:

let value = UIInterfaceOrientation.landscapeLeft.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
于 2017-07-21T07:55:50.210 回答