iOS保持纵向状态栏

我有一个使用接近传感器的应用程序,但接近传感器不能在横向模式下工作。 我听说,如果你保持在纵向模式状态栏它的传感器将工作我试过这个,但它没有奏效。

[[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait animated:NO]; 

状态栏仍然切换到横向模式。

我该怎么办?

如果你想保持你的应用程序在纵向模式,无论DeviceOrientation,我会build议你添加下面的代码到你的viewController。

 - (BOOL) shouldAutorotate{ return NO; } - (NSUInteger) supportedInterfaceOrientations{ return UIInterfaceOrientationMaskPortrait; } - (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationPortrait; } 

这将确保您的应用程序将以纵向模式启动,并保持纵向模式,即使设备已打开。

编辑:为了保持应用程序在横向上,而只有一个肖像模式的观点,将上面的代码添加到一个viewController,你想限制到肖像模式。

将以下函数添加到您的appDelegate中:

 - (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window{ /* This is in order to allow views that do not support landscape mode to be able to load in */ return UIInterfaceOrientationMaskAll; } 

将以下代码添加到其他视图控制器:

 - (BOOL) shouldAutorotate{ return YES; } - (NSUInteger) supportedInterfaceOrientations{ return UIInterfaceOrientationMaskLandscape; } - (UIInterfaceOrientation) preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationLandscapeRight; //you can choose either landscape orientation here } 

我build议你使用这个层次结构:

  • RootViewController – 它将包含参考(最好是强)您的接近传感器,我build议你运行在后台线程。 这将只支持肖像模式,所以你的接近传感器将工作正常(我希望)。
  • displayViewController – 它将包含您拥有的所有UI元素,并且仅支持横向模式
  • 你可以通过使用委托pipe理他们之间的沟通

此外,在RootViewController的viewDidApper之后,请使用presentViewController(iOS 6.0及以上)或presentModalViewController(iOS 5.x)select器在屏幕上添加displayViewController的视图。 使用[self.view addSubview: displayViewController.view]; 将无法工作(我从个人经验发言)。