首页 > 解决方案 > 检测横向方向左或右

问题描述

我的应用程序支持纵向和横向-> 左右。我能够检测到它的景观。但无法检测到左或右。这是我的代码

if UIDevice.current.orientation.isLandscape {
// Do some task 
}

当用户旋转设备时,我需要检测用户是否旋转到横向或横向!

在我的上述情况下,我需要检查它的左侧还是右侧。我怎样才能检测到呢?

谢谢

标签: iosswiftiphonexcodeorientation

解决方案


我想你正在寻找这样的东西

    if UIDevice.current.orientation == UIDeviceOrientation.landscapeLeft {


    } else if UIDevice.current.orientation == UIDeviceOrientation.landscapeRight {

    } else {
        //not landscape left or right
    }

编辑 - - - -

根据您的评论,您正在寻找界面方向而不是设备方向。

override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
    var text=""
    switch UIDevice.current.orientation{
    case .portrait:
        text="Portrait"
    case .portraitUpsideDown:
        text="PortraitUpsideDown"
    case .landscapeLeft:
        text="LandscapeLeft"
    case .landscapeRight:
        text="LandscapeRight"
    default:
        text="Another"
    }
    NSLog("You have moved: \(text)")        
}

上面的代码检测界面方向...注意 switch 语句如何仍然使用 UIDeviceOrientation

以下是您可能要使用的另一种方法

override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
    if UIDevice.current.orientation.isLandscape {
        print("landscape")
    } else {
        print("portrait")
    }
}

再次注意 UIDevice Orientation 仍然使用......

下面是一个非常不同但有效的方法。

struct DeviceInfo {
struct Orientation {
    // indicate current device is in the LandScape orientation
    static var isLandscape: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isLandscape
                : UIApplication.shared.statusBarOrientation.isLandscape
        }
    }
    // indicate current device is in the Portrait orientation
    static var isPortrait: Bool {
        get {
            return UIDevice.current.orientation.isValidInterfaceOrientation
                ? UIDevice.current.orientation.isPortrait
                : UIApplication.shared.statusBarOrientation.isPortrait
        }
    }
}}

推荐阅读