如何在iPhone中通过编程检查设备的方向?

27

可能是重复问题:
iPhone方向

如何在iPhone上编程检查设备在任何时间点的方向?

谢谢。


1
可能有重复的问题 iPhone方向 - beryllium
请尝试访问此链接:http://jayprakashdubey.blogspot.in/2014/07/check-device-orientation.html - Jayprakash Dubey
你可以使用类似willTransitionToTraitCollection:withTransitionCoordinator:的方法。每当视图控制器的特征集合发生变化时,都会调用此方法。特征可以是水平和垂直大小类。因此,在该方法内部,我们可以检查以下内容(在Swift中):switch newCollection.verticalSizeClass { case .Compact: //它是横屏 case .Regular, .Unspecified: //它是竖屏 } - angelos.p
6个回答

74

这里有两个宏 UIDeviceOrientationIsLandscapeUIDeviceOrientationIsPortrait

因此,你可以像这样同时检查它们...

   if (UIDeviceOrientationIsLandscape([UIDevice currentDevice].orientation))
    {
         // code for landscape orientation      
    }

或者

    if (UIDeviceOrientationIsPortrait([UIDevice currentDevice].orientation))
    {
         // code for Portrait orientation       
    }

这个方法非常好用,但是对我来说只在viewDidAppear方法中有效。我正在使用storyboard。这样正确吗? - Felipe FMMobile
2
这在iOS8中再次不起作用。 - LiangWang

17

试一试。

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

9

还可以尝试:

UIInterfaceOrientationIsPortrait(orientation)

并且

UIInterfaceOrientationIsLandscape(orientation)

7

-[UIViewController interfaceOrientation]

这个方法可以获取当前界面的方向。

不过,我们也可以从设备中获取设备方向,而与当前界面的方向无关:

[[UIDevice currentDevice] orientation]

详细信息请参阅文档,但是为了让它起作用,您需要做更多的工作。


4
您可以在函数内进行检查。
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations

    if(interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {
       //do for portrait
    }       
    else 
    { 
       //do for Landscape 
    }
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || 
            interfaceOrientation == UIInterfaceOrientationPortrait || 
            interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}

3

您应该在AppDelegate didFinishLaunchingWithOptions中放置[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

然后,在您的应用程序的任何位置,您可以使用以下代码获取当前方向:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

并且可以使用以下代码测试方向:

UIInterfaceOrientationIsPortrait(orientation) UIInterfaceOrientationIsLandscape(orientation)


你应该使用 UIDeviceOrientationIsLandscape 来测试变量 orientation,而不是使用 UIInterfaceOrientationIsLandscape - Webdevotion

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接