How can I detect and apply landscape orientation to AVCaptureVideoPreviewLayer in Swift?
Detect and apply it at viewWillLayoutSubviews
or if you're using UIView subclass in layoutSubviews
.
Here's how:
override func viewWillLayoutSubviews() { let orientation: UIDeviceOrientation = UIDevice.current.orientation previewLayer.connection?.videoOrientation = { switch (orientation) { case .portrait: return .portrait case .landscapeRight: return .landscapeLeft case .landscapeLeft: return .landscapeRight default: return .portrait } }()}
update for Swift 3
override func viewWillLayoutSubviews() { let orientation: UIDeviceOrientation = UIDevice.current.orientation print(orientation) switch (orientation) { case .portrait: videoPreviewLayer?.connection.videoOrientation = .portrait case .landscapeRight: videoPreviewLayer?.connection.videoOrientation = .landscapeLeft case .landscapeLeft: videoPreviewLayer?.connection.videoOrientation = .landscapeRight case .portraitUpsideDown: videoPreviewLayer?.connection.videoOrientation = .portraitUpsideDown default: videoPreviewLayer?.connection.videoOrientation = .portraitUpsideDown }}
For me I need it to change orientation when I rotate iPad left or right, the solution that helped me is:
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { let orientation = UIDevice.current.orientation switch (orientation) { case .portrait: videoPreviewLayer?.connection.videoOrientation = .portrait case .landscapeLeft: videoPreviewLayer?.connection.videoOrientation = .landscapeRight case .landscapeRight: videoPreviewLayer?.connection.videoOrientation = .landscapeLeft default: videoPreviewLayer?.connection.videoOrientation = .portrait }}