在SwiftUI中取消WKWebView



我是Swift的新手,正在使用SwiftUI构建应用程序。

我正在使用与下面所写内容类似的代码显示WKWebView。

struct SomeView: View {
@State var showWebView = false
var body: some View {
ZStack {
Button(action: {
self.showWebView.toggle()
}) {
Text("Go To WebView")
.padding()
.foregroundColor(.black)
.font(.title)
}
.sheet(isPresented: $showWebView, content: {
WebView(url: "https://www.apple.com/")
})
}
}
}
struct WebView: UIViewRepresentable {
var url: String
func makeCoordinator() -> Coordinator {
return Coordinator()
}
func makeUIView(context: Context) -> WKWebView {
let webView = WKWebView()
return webView
}
func updateUIView(_ uiView: WebView.UIViewType, context: UIViewRepresentableContext<WebView>) {
let urlRequest = URLRequest.init(url: URL.init(string: self.url)!)
uiView.navigationDelegate = context.coordinator
uiView.load(urlRequest)
}
}
class Coordinator: NSObject, WKNavigationDelegate {
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if let url = navigationAction.request.url?.absoluteString {
if url.contains("apple") {
let someViewModel = SomeViewModel()
someViewModel.processRequest(url: url)
}
}
decisionHandler(.allow)
}
}

代码按预期工作。我可以显示WKWebView,显示所需的网站。然而,我很难弄清楚如何在调用someViewModel.processRequest()后关闭WKWebView并导航到另一个页面。你能帮忙吗?

我会做整个WebView的事情有点不同,这应该(就我理解你的问题而言(解决你的情况:

import SwiftUI
import SafariServices
struct SomeView: View {
@State var showWebView = false
var body: some View {
ZStack {
Button(action: {
self.showWebView.toggle()
}) {
Text("Go To WebView")
.padding()
.foregroundColor(.black)
.font(.title)
}
.sheet(isPresented: $showWebView, content: {
WebView(url: URL(string: "https://www.apple.com/")!) })
}
}
}
struct WebView: UIViewControllerRepresentable {
let url: URL
func makeUIViewController(context: UIViewControllerRepresentableContext<WebView>) -> SFSafariViewController {
return SFSafariViewController(url: url)
}
func updateUIViewController(_ uiViewController: SFSafariViewController, context: UIViewControllerRepresentableContext<WebView>) {
}
}

相关内容

  • 没有找到相关文章

最新更新