首页 > 解决方案 > 当设备方向为 faceDown 或 faceUp 时如何获取界面方向?

问题描述

AVCaptureVideoOrientation通过获取当前设备方向来设置方向,但是当设备为 faceDown 或 faceUp 时,我无法获取界面方向。任何帮助将不胜感激。提前致谢

private func configureDeviceOrientation() {
    var videoOrientation: AVCaptureVideoOrientation {
        switch UIDevice.current.orientation {
        case .faceUp, .faceDown:
            //I don't know whether the interface orientation is landscapeLeft
            //or landscapeRight nor do I know how to check.
    }
}

interfaceOrientation已从 iOS 8 弃用,这是一个框架,因此我无权访问UIApplication.shared

标签: iosswift

解决方案


我的AVCaptureVideoOrientation.

只需使用self.view.window?.windowScene?.interfaceOrientation代替UIDevice.current.orientation

switch self.view.window?.windowScene?.interfaceOrientation {
    case .portrait:
        previewLayer.connection?.videoOrientation = .portrait
    case .portraitUpsideDown:
        previewLayer.connection?.videoOrientation = .portraitUpsideDown
    case .landscapeRight:
        previewLayer.connection?.videoOrientation = .landscapeRight
    case .landscapeLeft:
        previewLayer.connection?.videoOrientation = .landscapeLeft
    default:
        print("other")
}

此值将是纵向、纵向向上、横向右或横向左。

在启动时以及每次设备改变方向时调用此代码。

有关文档,请参见此处


推荐阅读