使用 onChange 方法关闭 UIViewRepresentable 无效

Dismiss UIViewRepresentable using onChange method is Not working

我有一个 UIViewRepresentable 并且当某些值 changed.I 使用了 .onChange 方法并且它不工作时需要关闭。但是onChange方法调用成功。

主视图

class ViewModel:ObservableObject {
    @Published var urlHasChanged:Bool = false
    @Published var isShowWebView:Bool = false
}

struct MainView : View {
    @ObservedObject var viewModel = ViewModel()
    @Environment(\.presentationMode) var presentationMode

    var body: some View {
        NavigationView {
            VStack {
                Button {
                    viewModel.isShowWebView = true
                } label: {
                    Text("show web view")
                }
                .background(NavigationLink( destination:
                                                WebView(viewModel: viewModel)
                    .onChange(of: viewModel.urlHasChanged, perform: { newValue in
                        print("called")
                        self.presentationMode.wrappedValue.dismiss()
                    })
                    ,isActive: $viewModel.isShowWebView, label: {
                    EmptyView()
                }).opacity(0))

            }
        }
    }

}

UIViewRepresentable

struct WebView: UIViewRepresentable {

    var viewModel : ViewModel

    func makeCoordinator() -> Coordinator {
        return Coordinator()
    }

    func makeUIView(context: Context) -> WKWebView {
        let webView = WKWebView()
        context.coordinator.viewModel = viewModel
        webView.navigationDelegate = context.coordinator
        webView.load(URLRequest(url: URL(string: "https://www.google.com/")!))
        return webView
    }

    func updateUIView(_ webView: WKWebView, context: Context) {
        let request = URLRequest(url: URL(string: "https://www.google.com/")!)
        webView.load(request)
    }


    class Coordinator : NSObject, WKNavigationDelegate {
        var viewModel : ViewModel?

        func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
            //print("webview url \(webView.url)")
        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            if let host = navigationAction.request.url?.absoluteString{
                if host.contains("google.com") {
                    decisionHandler(.allow)
                    return
                }else{
                    viewModel?.urlHasChanged = true
                    decisionHandler(.cancel)
                    return
                }
            }else{
                decisionHandler(.cancel)
            }
        }
    }
}

不是那个演示,而是把激活标志转回去,喜欢

.onChange(of: viewModel.urlHasChanged, perform: { newValue in
    print("called")
    viewModel.isShowWebView = false // << here !!
})