如何在iOS中从应用程序返回前景时更改设备方向?

时间:2016-01-13 04:50:37

标签: ios orientation landscape portrait

当我使用以下代码成功转到第二个视图控制器时,我已将方向从纵向更改为横向:

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

但是当我进入后台并在第二个视图控制器中返回前景时,我按下按钮转到第一个视图控制器。我正在使用以下代码将方向从横向更改为纵向,但它无效。

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

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    if ([ConfigObjC currentPage] && [[ConfigObjC currentPage] isEqualToString:@"SubViewController"])
    {
        return UIInterfaceOrientationMaskLandscapeLeft;
    }
    else{
        return UIInterfaceOrientationMaskPortrait;
    }
}

如果我不转到后台,则上述代码有效。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

进入forground模式时尝试此操作 -

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

if ( ([[UIDevice currentDevice] orientation] ==  UIDeviceOrientationPortrait)  )
{
   // do something for Portrait mode
}
else if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) || ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft))
{
   // do something for Landscape mode
}

答案 1 :(得分:0)

You have to enable notification for orientation.

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

And when you come in foreground from background.
Add your check here Like:


if ( ([[UIDevice currentDevice] orientation] ==  UIDeviceOrientationPortrait)  )
{
   //Rotate in Landscape mode
}
else if(([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight) || ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationLandscapeLeft))
{
   //Rotate in Portrait mode
}