我正在我的应用程序中构建一个二维码阅读器,到目前为止,我将其作为工作表打开,并在检测到二维码/条形码时关闭。
应用程序的阅读器部分使用 UIKit,我有文件 QRCodeScan.swift
,它是 UIViewControllerRepresentable
,QR 扫描器返回它找到的代码的值该文件中的协调员。
我似乎找不到任何方法将找到的代码从协调器中取出到原始 View 中。
这是 QRCodeScan 文件。
struct QRCodeScan: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
func makeUIViewController(context: Context) -> ScannerViewController {
let vc = ScannerViewController()
vc.delegate = context.coordinator
return vc
}
func updateUIViewController(_ vc: ScannerViewController, context: Context) {
}
class Coordinator: NSObject, QRCodeScannerDelegate {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
func codeDidFind(_ foundCode: String) {
print(foundCode)
/*this is where the code comes to, need to return it from here */
presentationMode.wrappedValue.dismiss()
}
var parent: QRCodeScan
init(_ parent: QRCodeScan) {
self.parent = parent
}
}
}
这是调用 qr 阅读器的 ContentView 的裁剪版本,这是我需要将找到的代码放回的地方
struct ContentView: View {
@State var presentQRScanner = false
var body: some View {
NavigationView{
Form{
Section(header: Text("Info")){
Button("Scan Barcode"){
self.presentQRScanner = true
}
.sheet(isPresented: $presentQRScanner){QRCodeScan()}
}
}
.navigationBarTitle(Text("New"), displayMode: .large)
.navigationBarItems(trailing: Button("Save"){
print("Button Pressed")
})
}
}
}
我在这里遇到了一个完全的障碍,我找不到任何资源可以让我从协调器传回数据,也许我正在实现错误但我似乎无法采用任何其他解决方案适合
非常感谢任何帮助。
谢谢
最佳答案
您可能已经解决了这个问题,但解决方案是在 ContentView 中使用 @State 变量链接到 QRCodeScan 结构和 Coordinator 类中的 @Binding 变量。
查看此答案:Accessing MKMapView elements as UIViewRepresentable in the main (ContentView) SwiftUI view
这样的事情应该可以解决问题,但我建议阅读我链接的更详细的答案:
struct QRCodeScan: UIViewControllerRepresentable {
@Binding var code: String
func makeCoordinator() -> Coordinator {
return Coordinator(code: $code)
}
func makeUIViewController(context: Context) -> ScannerViewController {
let vc = ScannerViewController()
vc.delegate = context.coordinator
return vc
}
func updateUIViewController(_ vc: ScannerViewController, context: Context) {
}
class Coordinator: NSObject, QRCodeScannerDelegate {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
@Binding var code: String
init(code: Binding<String>) {
_code = code
}
func codeDidFind(_ foundCode: String) {
print(foundCode)
/*this is where the code comes to, need to return it from here */
self.code = foundCode
presentationMode.wrappedValue.dismiss()
}
var parent: QRCodeScan
init(_ parent: QRCodeScan) {
self.parent = parent
}
}
}
在您的 ContentView 中,创建 @State var 代码,然后您可以调用 QRCodeScan(code: $code)。
关于SwiftUI 将数据从协调器中获取到内容 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58437825/