如何让iPhone面向当前?

Kno*_*del 43 objective-c accelerometer

是否有一种特殊的方法来获得iPhone定位?我不需要它在度或弧度,我希望它返回一个UIInterfaceOrientation对象.我只需要它来构建if-else结构

if(currentOrientation==UIInterfaceOrientationPortrait ||currentOrientation==UIInterfaceOrientationPortraitUpsideDown) {
//Code
}  
if (currentOrientation==UIInterfaceOrientationLandscapeRight ||currentOrientation==UIInterfaceOrientationLandscapeLeft ) {
//Code
}
Run Code Online (Sandbox Code Playgroud)

提前致谢!

Sat*_*jit 114

这很可能是你想要的:

UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用系统宏,如:

if (UIInterfaceOrientationIsPortrait(interfaceOrientation))
{

}
Run Code Online (Sandbox Code Playgroud)

如果您想使用设备方向:

UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];
Run Code Online (Sandbox Code Playgroud)

这包括像UIDeviceOrientationFaceUp和的枚举UIDeviceOrientationFaceDown

  • 这在技术上是错误的,您从方法调用中获取UIDeviceOrientation并将其存储在UIInterfaceOrientation中.UIInterfaceOrientation是4中的一个,表示您的界面的外观.UIDeviceOrientation是6个中的一个(包括平躺和平放)并告诉您设备的方向,而不一定是您的界面的样子.您的界面可能处于纵向模式,但如果设备位于桌面上,则会返回UIDeviceOrientationFaceUp. (29认同)
  • @CoryImdieke:感谢您更新设备和界面方向之间的差异.UIInterfaceOrientation currentOrientation = [[UIApplication sharedApplication] statusBarOrientation]; 是正确的API (12认同)
  • 这在技术上是错误的我同意@Cory但是确实工作得很好.我将在下面发布一个不会出错的方法,并且是相同的概念. (2认同)
  • `statusBarOrientation` 现在已弃用。 (2认同)

Bji*_*nse 11

如其他答案中所述,您需要interfaceOrientation,而不是deviceOrientation.

最简单的方法是在UIViewController上使用属性interfaceOrientation.(所以大多数情况下,只是:self.interfaceOrientation会这样做).

可能的值是:

UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeLeft
Run Code Online (Sandbox Code Playgroud)

请记住:将设备向右转,即可进入左方向.