当设备方向朝下或朝上时,如何获取接口方向?

  • 本文关键字:方向 何获 取接口 ios swift
  • 更新时间 :
  • 英文 :


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

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

我的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")
}

此值将为纵向、纵向颠倒、横向右或横向左。

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

有关文档,请参阅此处。

添加到视图将出现以检查设备是否旋转:

//Observer for if Device Rotated
NotificationCenter.default.addObserver(self,
selector: #selector(device_rotated),
name:UIDevice.orientationDidChangeNotification,
object: nil)

添加到视图将消失:

NotificationCenter.default.removeObserver(self)

添加到视图控制器。 如果设备旋转或方向更改,将调用函数:

@objc func device_rotated(notification:Notification) -> Void{
switch UIDevice.current.orientation {
case .landscapeLeft, .landscapeRight:
print("Landscape")
case .portrait, .portraitUpsideDown:
print("Portrait")
case .faceUp:
print("Face Up")
case .faceDown:
print("Face Down")
default:
print("Default")
}
}

最新更新