SwiftUI实战-WKWebView的使用
2022-05-05 本文已影响0人
ISwiftUI
ContentView.swift
import SwiftUI
struct ContentView: View {
@State var url: String? = "https://www.baidu.com"
var body: some View {
SWKWebView(url: $url)
}
}
SWKWebView.swift
import SwiftUI
import WebKit
struct SWKWebView: UIViewRepresentable {
@Binding var url: String?
func makeUIView(context: Context) -> WKWebView {
let webview = WKWebView()
webview.navigationDelegate = context.coordinator
return webview
}
func updateUIView(_ uiView: WKWebView, context: Context) {
if let url = url, let requetURL = URL(string: url) {
uiView.load(URLRequest(url: requetURL))
}
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
class Coordinator: NSObject,WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.title") { (result, error) in
print("didFinish:\(String(describing: result ?? ""))")
}
}
}
}