如何在 iOS 中将应用程序 returns 从后台转到前台时更改设备方向?

How to change device orientation when app returns to foreground from background in iOS?

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

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

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

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;
    }
}

如果我不去后台,上面的代码是有效的。我该如何解决这个问题?

进入前台模式时试试这个-

[[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
}
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
}