如何在iPhone中以编程方式检查设备的方向?

时间:2010-08-30 12:00:28

标签: iphone objective-c ios ipad

  

可能重复:
  iPhone orientation

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

谢谢。

6 个答案:

答案 0 :(得分:71)

以下是宏UIDeviceOrientationIsLandscapeUIDeviceOrientationIsPortrait

所以请单独检查,你可以这样做......

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

OR

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

答案 1 :(得分:15)

试试吧。

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

答案 2 :(得分:8)

另请尝试:

UIInterfaceOrientationIsPortrait(orientation)

UIInterfaceOrientationIsLandscape(orientation)

答案 3 :(得分:7)

-[UIViewController interfaceOrientation]

但是,可以独立于当前界面方向检索deviceOrientation:

[[UIDevice currentDevice] orientation]

阅读文档以获取更多信息,但您需要做更多的事情才能使其发挥作用。

答案 4 :(得分: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);
}

答案 5 :(得分:3)

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

然后,在您的应用程序中的任何位置,您都可以通过以下方式获取当前方向:

UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];

测试方向:

UIInterfaceOrientationIsPortrait(orientation) UIInterfaceOrientationIsLandscape(orientation)