我在一个VNDocumentCameraViewController
称为嵌入UIViewControllerRepresentable
的视图中作为第二个屏幕。在关闭(取消或保存扫描)时,我希望选项卡视图返回到我的第一个屏幕。那部分就像一个魅力。ScanView
TabView
VNDocumentCameraViewController
我的问题是,当回到我的. 时VNDocumentCameraViewController
,我想重新实例化该控制器并重新开始——这是我无法弄清楚如何实现的。
我知道我ContentView
保留对 的引用ScanView
是为什么 myUIViewControllerRepresentable
没有被重新实例化——我怎样才能手动做到这一点?
这是代码:
import SwiftUI
@main
struct so_VisionKitInTabsApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State private var tabSelection = 1
var body: some View {
TabView(selection: $tabSelection) {
Text("First View")
.tabItem { Text("First View") }
.tag(1)
ScanView(tabSelection: $tabSelection)
.tabItem { Text("Scan View") }
.tag(2)
}
}
}
import VisionKit
struct DocumentScanningViewAdapter: UIViewControllerRepresentable {
typealias UIViewControllerType = VNDocumentCameraViewController
let onDismiss: () -> ()
func makeCoordinator() -> Coordinator {
Coordinator(parent: self)
}
func makeUIViewController(context: Context) -> VNDocumentCameraViewController {
let vc = VNDocumentCameraViewController()
vc.delegate = context.coordinator
return vc
}
func updateUIViewController(_ uiViewController: VNDocumentCameraViewController, context: Context) { }
class Coordinator: NSObject, VNDocumentCameraViewControllerDelegate {
var parent: DocumentScanningViewAdapter
init(parent: DocumentScanningViewAdapter) {
self.parent = parent
}
func documentCameraViewController(_ controller: VNDocumentCameraViewController, didFinishWith scan: VNDocumentCameraScan) {
print("Finished successfully…")
parent.onDismiss()
}
func documentCameraViewControllerDidCancel(_ controller: VNDocumentCameraViewController) {
print("Cancelled…")
resetCoordinator(for: controller)
parent.onDismiss()
}
func resetCoordinator(for controller: VNDocumentCameraViewController) {
controller.delegate = parent.makeCoordinator()
}
}
}
struct ScanView: View {
@Binding var tabSelection: Int
var body: some View {
DocumentScanningViewAdapter(onDismiss: { tabSelection = 1 })
}
}