如何在 iOS 上检测设备的方向?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5559652/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:28:21  来源:igfitidea点击:

How Do I detect the orientation of the device on iOS?

iosobjective-corientationuidevice

提问by JusmanX

I have a question on how to detect the device orientation on iOS. I don't need to receive change notifications, just the current orientation itself. This seems to be a rather simple question, but I haven't been able to wrap my head around it. Below is what I have done so far:

我有一个关于如何在 iOS 上检测设备方向的问题。我不需要接收更改通知,只需接收当前方向本身。这似乎是一个相当简单的问题,但我一直无法解决它。以下是我到目前为止所做的:

UIDevice *myDevice = [UIDevice currentDevice] ;
[myDevice beginGeneratingDeviceOrientationNotifications];
UIDeviceOrientation deviceOrientation = myDevice.orientation;
BOOL isCurrentlyLandscapeView = UIDeviceOrientationIsLandscape(deviceOrientation);
[myDevice endGeneratingDeviceOrientationNotifications];

In my mind this should work. I enable the device to receive device orientation notices, then ask for what orientation it is in, but then it is not working and I don't know why.

在我看来,这应该有效。我使设备能够接收设备方向通知,然后询问它所处的方向,但它不起作用,我不知道为什么。

回答by Moe

Really old thread, but no real solution.

真的很老的线程,但没有真正的解决方案。

I Had the same problem, but found out that getting The UIDeviceOrientation isn't always consistent, so instead use this:

我遇到了同样的问题,但发现获取 UIDeviceOrientation 并不总是一致的,所以改用这个:

UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;

if(orientation == 0) //Default orientation 
    //UI is in Default (Portrait) -- this is really a just a failsafe. 
else if(orientation == UIInterfaceOrientationPortrait)
    //Do something if the orientation is in Portrait
else if(orientation == UIInterfaceOrientationLandscapeLeft)
    // Do something if Left
else if(orientation == UIInterfaceOrientationLandscapeRight)
    //Do something if right

回答by TONy.W

if UIViewController:

如果 UIViewController:

if (UIDeviceOrientationIsLandscape(self.interfaceOrientation))
{
    // 
}

if UIView:

如果 UIView:

if (UIDeviceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
{
    //
}

UIDevice.h:

UIDevice.h:

#define UIDeviceOrientationIsPortrait(orientation)  ((orientation) == UIDeviceOrientationPortrait || (orientation) == UIDeviceOrientationPortraitUpsideDown)
#define UIDeviceOrientationIsLandscape(orientation) ((orientation) == UIDeviceOrientationLandscapeLeft || (orientation) == UIDeviceOrientationLandscapeRight)

Updated:

更新

add this code to xxx-Prefix.pch then you can use it anywhere:

将此代码添加到 xxx-Prefix.pch 然后你可以在任何地方使用它:

// check device orientation
#define dDeviceOrientation [[UIDevice currentDevice] orientation]
#define isPortrait  UIDeviceOrientationIsPortrait(dDeviceOrientation)
#define isLandscape UIDeviceOrientationIsLandscape(dDeviceOrientation)
#define isFaceUp    dDeviceOrientation == UIDeviceOrientationFaceUp   ? YES : NO
#define isFaceDown  dDeviceOrientation == UIDeviceOrientationFaceDown ? YES : NO

usage:

用法:

if (isLandscape) { NSLog(@"Landscape"); }

回答by Saurabh Prajapati

For what You looking for first you have to Get Notification if Orientation Changed! You Can set This Thing in viewDidLoad like

对于您首先要寻找的内容,如果方向改变,您必须获得通知!你可以在 viewDidLoad 中设置这个东西

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(OrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];

and whenever Orientation of your Device changed OrientationDidChangeCalled where You can do whatever You Want as Per Orientation

并且每当您的设备的方向改变OrientationDidChange调用时,您可以根据方向做任何您想做的事情

-(void)OrientationDidChange:(NSNotification*)notification
{
    UIDeviceOrientation Orientation=[[UIDevice currentDevice]orientation];

    if(Orientation==UIDeviceOrientationLandscapeLeft || Orientation==UIDeviceOrientationLandscapeRight)
    {
    }
    else if(Orientation==UIDeviceOrientationPortrait)
    {
    }
}

回答by rafalkitta

If you want to get device orientationdirectly from accelerometer use [[UIDevice currentDevice] orientation]. But if you need current orientation of your application(interface orientation) use [[UIApplication sharedApplication] statusBarOrientation].

如果您想直接从加速度计获取设备方向,请使用[[UIDevice currentDevice] orientation]. 但是,如果您需要应用程序的当前方向(界面方向),请使用[[UIApplication sharedApplication] statusBarOrientation].

回答by Jasarien

UIViewControllerhas an interfaceOrientationproperty that you can access to find out the current orientation of a view controller.

UIViewController有一个interfaceOrientation属性,你可以访问它来找出视图控制器的当前方向。

As for your example, that should work. When you say it isn't working, what do you mean? What results does it give you versus what you expected?

至于你的例子,那应该有效。当你说它不起作用时,你是什么意思?与您的预期相比,它给了您什么结果?

回答by Ashok R

In Swift 3.0

在 Swift 3.0 中

to get device orientation.

获取设备方向。

/* return current device orientation.
   This will return UIDeviceOrientationUnknown unless device orientation notifications are being generated. 
*/
UIDevice.current.orientation

to get device orientation from your app

从您的应用程序获取设备方向

UIApplication.shared.statusBarOrientation

回答by Nicolas Lauquin

Wasn't satisfied by "UIDeviceOrientation"because when a UIViewcontroller orientation is fixed to a specific orientation you don't get a pertinent information with the device orientation, so the right thing to do is using "UIInterfaceOrientation".

"UIDeviceOrientation"不满意,因为当 UIViewcontroller 方向固定为特定方向时,您不会获得与设备方向相关的信息,因此正确的做法是使用"UIInterfaceOrientation"

You can get the orientation from the UIViewController with a "self.interfaceOrientation", but when you are factorizing our code, you might need to do this kind of test outside a view controller, (custom view, a category…), so you still can access the information anywhere outside the controller by using the rootviewController:

您可以使用"self.interfaceOrientation"从 UIViewController 获取方向,但是当您分解我们的代码时,您可能需要在视图控制器之外进行此类测试(自定义视图、类别...),因此您仍然可以使用rootviewController访问控制器之外的任何地方的信息:

if (UIInterfaceOrientationIsLandscape(view.window.rootViewController.interfaceOrientation)) {
}

回答by FlySoFast

There's a way to achieve this whether the orientation lock is enabled or notby using data from CoreMotion. This is the code:

无论是否启用方向锁定,都有一种方法可以通过使用来自 CoreMotion 的数据来实现这一点。这是代码:

#import <CoreMotion/CoreMotion.h> 

    CMMotionManager *cm=[[CMMotionManager alloc] init];
    cm.deviceMotionUpdateInterval=0.2f;
    [cm startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue]
                            withHandler:^(CMDeviceMotion *data, NSError *error) {

                            if(fabs(data.gravity.x)>fabs(data.gravity.y)){
                                    NSLog(@"LANSCAPE");
                                if(data.gravity.x>=0){
                                    NSLog(@"LEFT");
                                }
                                else{
                                    NSLog(@"RIGHT");
                                }

                        }
                        else{
                                NSLog(@"PORTRAIT");
                                if(data.gravity.y>=0){
                                    NSLog(@"DOWN");
                                }
                                else{

                                    NSLog(@"UP");
                                }

                            }

}];

回答by Beninho85

Here is some Swift variables to make detection easier:

这里有一些 Swift 变量可以让检测更容易:

let LANDSCAPE_RIGHT: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeRight
let LANDSCAPE_LEFT: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.LandscapeLeft
let LANDSCAPE: Bool = LANDSCAPE_LEFT || LANDSCAPE_RIGHT
let PORTRAIT_NORMAL: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.Portrait
let PORTRAIT_REVERSE: Bool = UIDevice.currentDevice().orientation == UIDeviceOrientation.PortraitUpsideDown
let PORTRAIT: Bool = PORTRAIT_REVERSE || PORTRAIT_NORMAL

回答by Martin Lütke

Have you unlocked the hardware lock for device orientation? There is one at the edge of my iPad 1.

您是否已解锁设备方向的硬件锁?我的 iPad 1 边缘有一个。