SwiftUI 5:如何锁定特定视图的方向
Posted
技术标签:
【中文标题】SwiftUI 5:如何锁定特定视图的方向【英文标题】:SwiftUI 5: How to lock orientation for a specific view 【发布时间】:2021-12-04 09:28:08 【问题描述】:在我的相机视图中,我想将方向保持为纵向,因为当它处于横向时,相机预览不会旋转:
struct CameraPreview: UIViewRepresentable
@ObservedObject var camera: CameraModel
func makeUIView(context: Context) -> some UIView
let view = UIView(frame: UIScreen.main.bounds)
camera.preview = AVCaptureVideoPreviewLayer(session: camera.session)
//...
camera.preview.videoGravity = .resizeAspectFill
camera.preview.frame = view.frame
view.layer.addSublayer(camera.preview)
// starting session
camera.session.startRunning()
return view
func updateUIView(_ uiView: UIViewType, context: Context)
我知道我迟早需要解决这个问题,但我需要行动起来。现在,我将阻止所有其他方向,除了:
struct CameraView: View
init()
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
[..]
通过执行上述操作,当放置在横向时,相机预览会减半,然后 init
“开始”将其设置回 CameraView 回到纵向。如何让它在没有任何动画的情况下保持纵向模式?
将代码放在.onAppear
中没有任何作用:
struct CameraView: View
var body: some View
VStack..
.onAppear(perform:
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
【问题讨论】:
【参考方案1】:原来我已经修复了旋转:
func updateUIView(_ uiView: UIViewType, context: Context)
let view = UIView(frame: UIScreen.main.bounds)
let statusBarOrientation = UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
let videoOrientation: AVCaptureVideoOrientation = statusBarOrientation?.videoOrientation ?? .portrait
camera.preview.frame = view.frame
camera.preview.connection?.videoOrientation = videoOrientation
对于videoOrientation
,请参阅Jack's answer。
import AVFoundation
extension UIInterfaceOrientation
var videoOrientation: AVCaptureVideoOrientation?
switch self
case .portraitUpsideDown: return .portraitUpsideDown
case .landscapeRight: return .landscapeRight
case .landscapeLeft: return .landscapeLeft
case .portrait: return .portrait
default: return nil
【讨论】:
以上是关于SwiftUI 5:如何锁定特定视图的方向的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI - 如何在 SwiftUI 中弹出到特定视图?
文本视图的 lineBreakMode 是不是有 SwiftUI 等效项?
如何在 SwiftUI 中将滚动视图添加到屏幕的特定部分? [复制]