在 SwiftUI 中关闭 WKWebView
Posted
技术标签:
【中文标题】在 SwiftUI 中关闭 WKWebView【英文标题】:Dismiss WKWebView in SwiftUI 【发布时间】:2020-08-19 23:57:52 【问题描述】:我是 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 并导航到另一个页面。你能帮忙吗?
【问题讨论】:
【参考方案1】:我会对整个 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>)
【讨论】:
以上是关于在 SwiftUI 中关闭 WKWebView的主要内容,如果未能解决你的问题,请参考以下文章
SwiftUI:在 macOS NavigationView 中关闭视图
如何在 SwiftUI 中关闭 ResearchKit 模态视图?