我想知道如何在WKWebView
上显示当前URL,并在URL更改时更新。目前我添加了一个Text()
,但它根本不显示URL。有什么办法可以解决吗?
WebView
import SwiftUI
import WebKit
struct WebView : UIViewRepresentable {
let request: URLRequest
private var webView: WKWebView?
init (request: URLRequest) {
self.webView = WKWebView()
self.request = request
}
func makeUIView(context: Context) -> WKWebView {
webView?.load(request)
return webView!
}
func updateUIView(_ uiView: WKWebView, context: Context) {
}
func URL() -> String {
return (webView?.url)?.absoluteString ?? ""
}
func goBack() {
webView?.goBack()
}
func goForward() {
webView?.goForward()
}
}
主视图
struct MainView: View {
var webView: WebView = WebView(request: URLRequest(url: URL(string: "https://www.google.com")!))
var body: some View {
VStack {
//...
Text(webView.URL())
webView
Button(action: { webView.goBack() }, label: { Text("Test") })
//...
}
}