UIInterfaceOrientation

UIInterfaceOrientation

我正在玩在Swift中使用AVFoundation

通常,当我设置摄像机捕获 session 时,我会在Objective-C中执行以下操作

[[cameraView.previewLayer connection] setVideoOrientation:(AVCaptureVideoOrientation)[self interfaceOrientation]]

快速看来,我必须做这样的事情(由于可选类型)
if let connection = cameraView.previewLayer?.connection {
  connection.videoOrientation = self.interfaceOrientation as AVCaptureVideoOrientation
}

但是这提示
‘AVCaptureVideoOrientation’ is not a subtype of ‘UIInterfaceOrientation’

在阅读了有关向下转换的方法论之后,这很有道理,但是我正在努力寻找如何真正实现这一点的方法。

我是否需要编写一个辅助方法,该方法基本上可以通过UIInterfaceOrientation的所有可用值来执行switch语句来使之正常工作?

最佳答案

正如我在评论中指出的那样,由于AVCaptureVideoOrientation和UIInterfaceOrientation与它们的大小写不匹配,因此可以使用以下方法:

extension AVCaptureVideoOrientation {
    var uiInterfaceOrientation: UIInterfaceOrientation {
        get {
            switch self {
            case .LandscapeLeft:        return .LandscapeLeft
            case .LandscapeRight:       return .LandscapeRight
            case .Portrait:             return .Portrait
            case .PortraitUpsideDown:   return .PortraitUpsideDown
            }
        }
    }

    init(ui:UIInterfaceOrientation) {
        switch ui {
        case .LandscapeRight:       self = .LandscapeRight
        case .LandscapeLeft:        self = .LandscapeLeft
        case .Portrait:             self = .Portrait
        case .PortraitUpsideDown:   self = .PortraitUpsideDown
        default:                    self = .Portrait
        }
    }
}

然后将其用作:
if let connection = cameraView.previewLayer?.connection {
    connection.videoOrientation = AVCaptureVideoOrientation(ui:self.interfaceOrientation)
}

关于ios - 在Swift中将UIInterfaceOrientation枚举转换为AVCaptureVideoOrientation,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24110610/

10-10 23:14