以编程方式更改设备方向为横向不起作用

所以我试图通过执行以下操作来强制更改设备的一部分代码:

if ([[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortrait || [[UIApplication sharedApplication] statusBarOrientation] == UIInterfaceOrientationPortraitUpsideDown){ [[UIApplication sharedApplication] setStatusBarOrientation:UIDeviceOrientationLandscapeLeft animated:NO]; } 

但是方向并没有改变。 为什么是这样? 基本上目前的方向是肖像,我希望它被迫在风景

如果Inder Kumar Rathore的build议起作用,那很好。 但文档描述的方向属性是只读的,所以如果它的工作,我不确定你可以依靠它在未来的工作(除非苹果做了聪明的事情,并改变这种情况;迫使方向的变化,无论如何用户目前正在拿着他们的设备,这是一个明显的function需求)。

作为替代,在viewDidLoad中插入的以下代码将成功(并且有点好奇地)强制定位(假设您已经将rAonitororateToInterfaceOrientation修改为推荐的roronoa zorro):

 if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) { UIWindow *window = [[UIApplication sharedApplication] keyWindow]; UIView *view = [window.subviews objectAtIndex:0]; [view removeFromSuperview]; [window addSubview:view]; } 

显然,如果用户当前正在以纵向方向握住他们的设备(因此推测您的shouldAutorotateToInterfaceOrientation被设置为仅横向(landscape)),并且如果用户将他们的设备保持为纵向模式,则该例程将把它移到横向。 如果您的shouldAutorotateToInterfaceOirentation设置为仅用于纵向,则只需将UIDeviceOrientationIsPortrait与UIDeviceOrientationIsLandscape交换即可。

出于某种原因,从主窗口中删除视图,然后重新添加它迫使它查询shouldAutorotateToInterfaceOrientation并正确设置方向。 鉴于这不是一个苹果认可的方法,也许应该避免使用它,但它适用于我。 你的旅费可能会改变。 但是这个讨论也是指其他技术。

在iOS7上完美工作

如果你想Potrait然后:

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

如果你想要风景:

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

如果设备处于横向模式,则无法强制设备进入纵向模式,反之亦然。您只能告诉应用程序处于横向模式或纵向模式的特定模式。您可以通过以下方式执行此操作: –

  1. 你应该实现shouldAutorotateToInterfaceOrientation

     - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return UIInterfaceOrientationIsLandscape(interfaceOrientation); } 
  2. 编辑pList。

    添加一个关键的UIInterfaceOrientation到你的plist,并根据你的需要改变它的属性为UIInterfaceOrientationLandscapeLeftUIInterfaceOrientationLandscapeRightUIInterfaceOrientationPortraitUpsideDown

编辑

这可能无法在iOS 7中工作,但它在以前版本的iOS中工作,所以现在降低这个答案是没有意义的。 这个问题在2年前就已经提出了,我当时就回答了这个问题,这是一个可行的解决scheme。

 [[UIDevice currentDevice] setOrientation: UIDeviceOrientationLandscapeLeft];