44

有没有一种特殊的方法来获取 iPhone 的方向?我不需要它的度数或弧度,我希望它返回一个 UIInterfaceOrientation 对象。我只需要它来进行 if-else 构造,例如

if(currentOrientation==UIInterfaceOrientationPortrait ||currentOrientation==UIInterfaceOrientationPortraitUpsideDown) {
//Code
}  
if (currentOrientation==UIInterfaceOrientationLandscapeRight ||currentOrientation==UIInterfaceOrientationLandscapeLeft ) {
//Code
}

提前致谢!

4

5 回答 5

118

这很可能是您想要的:

UIInterfaceOrientation interfaceOrientation = [[UIApplication sharedApplication] statusBarOrientation];

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

if (UIInterfaceOrientationIsPortrait(interfaceOrientation))
{

}

如果您希望设备方向使用:

UIDeviceOrientation deviceOrientation = [[UIDevice currentDevice] orientation];

这包括枚举,如UIDeviceOrientationFaceUpUIDeviceOrientationFaceDown

于 2010-03-25T19:36:08.773 回答
11

正如在其他答案中所讨论的,您需要 interfaceOrientation,而不是 deviceOrientation。

最简单的方法是使用 UIViewController 上的 interfaceOrientation 属性。(所以最常见的是: self.interfaceOrientation 就可以了)。

可能的值为:

UIInterfaceOrientationPortrait           = UIDeviceOrientationPortrait,
UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
UIInterfaceOrientationLandscapeLeft      = UIDeviceOrientationLandscapeRight,
UIInterfaceOrientationLandscapeRight     = UIDeviceOrientationLandscapeLeft

请记住:通过将设备向右转动来输入左侧方向。

于 2012-02-07T20:53:51.393 回答
4

这是我不得不编写的一段代码,因为当方向改变时,我在根视图中遇到了一些奇怪的问题......我你看到的只是调出应该调用但似乎确实是的方法。 ...这很好用,没有错误

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if ([[UIDevice currentDevice]orientation] == UIInterfaceOrientationLandscapeLeft){
        //do something or rather
        [self 
shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationLandscapeLeft];
        NSLog(@"landscape left");
    }
    if ([[UIDevice currentDevice]orientation] == UIInterfaceOrientationLandscapeRight){
        //do something or rather
        [self 
shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationLandscapeRight];
        NSLog(@"landscape right");
    }
    if ([[UIDevice currentDevice]orientation] == UIInterfaceOrientationPortrait){
        //do something or rather
        [self shouldAutorotateToInterfaceOrientation:UIInterfaceOrientationPortrait];
        NSLog(@"portrait");
    }
}
于 2012-04-16T23:58:29.577 回答
1

UIInterfaceOrientation现在已弃用,并且UIDeviceOrientation包含UIDeviceOrientationFaceUpUIDeviceOrientationFaceDown因此不能依赖于为您提供界面方向。

解决方案虽然很简单

if (CGRectGetWidth(self.view.bounds) > CGRectGetHeight(self.view.bounds)) {
    // Landscape
} else {
    // Portrait
}
于 2016-12-10T04:12:55.560 回答
0

随着[UIApplication statusBarOrientation]被弃用,你现在应该使用:

UIWindowScene *activeWindow = (UIWindowScene *)[[[UIApplication sharedApplication] windows] firstObject];

UIInterfaceOrientation orientation = [activeWindow interfaceOrientation] ?: UIInterfaceOrientationPortrait;
于 2020-08-11T22:45:17.547 回答