SwiftUI以编程方式从可表示形式返回到View

时间:2019-10-16 18:10:47

标签: swift uikit swiftui

我正在尝试在新的swift ui应用程序中设置一个二维阅读器。

我可以通过此行加载UIKit qr阅读器视图

NavigationLink(destination: QRCodeScan()){Text("Scan QR")}

这是我的ViewControllerRepresentable

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 {
    func codeDidFind(_ code: String) {
        print(code)
        //Go back to the last page, take 'code' with you
    }

    var parent: QRCodeScan

    init(_ parent: QRCodeScan) {
        self.parent = parent
    }
}

}

在“返回最后一页...”行中,我需要以编程方式返回到将用户发送到qr扫描仪的页面。该页面加载了导航后退按钮,我非常需要复制此按钮的行为以在需要时调用

感谢任何帮助/指针

tia

2 个答案:

答案 0 :(得分:2)

struct ContentView: View {
    @State var isActive = false
    @State var code = ""
    var body: some View {
        NavigationView {
            ZStack {
                NavigationLink(destination: DetailView(isActive: $isActive, code: $code), isActive: $isActive, label: { EmptyView() })
                Button(action: {
                    self.isActive.toggle()
                }, label: {
                    Text("navigate")
                })
            }
        }
    }
}
struct DetailView: View {

    @Binding var isActive: Bool
    @Binding var code: String

    var body: some View {
        Button(action: {
            self.code = "new code"
            self.isActive.toggle()
        }) {
            Text("Back")
        }
    }
}

这可能会帮助您,使用NavigationLink的isActive参数来回导航

答案 1 :(得分:0)

简短的答案是您现在不能这样做。没有绑定或环境值可以触发此操作。我的猜测是,您可以利用类似于presentationMode的某种环境价值,但目前尚无广告。

您可以尝试使用当前的presentationMode,但我真正的建议是将QR扫描仪显示为单页而非推式。从导航的角度来看,这实际上可能更有意义。为此,请在您的演示者中设置一个@State变量以在演示时进行处理。

@State var presentQRScanner = false

var body: some View {
    Button("Scan") {
        self.presentQRScanner = true
    }
    .sheet(isPresented: $presentQRScanner) { QRCodeScan() }
}

然后,当您要以编程方式关闭时,您的UIViewControllerRepresentable

@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

func scannedCode() {
    presentationMode.wrappedValue.dismiss()
}

或者,您也可以通过在QRCodeScan上创建一个闭包(由代码调用)来关闭演示者。

var onCodeScanned: (Code) -> Void = { _ in }

func scannedCode() {
    onCodeScanned(code)
}

和演示者中

var body: some View {
    Button("Scan") {
        self.presentQRScanner = true
    }
    .sheet(isPresented: $presentQRScanner) { 
        QRCodeScan(onCodeScanned: { 
            self.process($0)
            self.presentQRScanner = false
        })
    }
}

编辑:不知道isActive绑定,如果您仍然希望将视图推入导航堆栈而不是显示它,那么该绑定实际上应该对您有用。