将 javascript 注入 SwiftUI WebKit
Inject javascript into SwiftUI WebKit
如何将 SwiftUI WebKit 视图的文本大小设置为 @State 变量?我有这段代码可以让我在 SwiftUI
中使用 WebViews
import SwiftUI
import WebKit
struct WebView : UIViewRepresentable {
var url : URL;
func makeUIView(context: Context) -> WKWebView {
return WKWebView();
}
func updateUIView(_ uiView: UIViewType, context: Context) {
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}
我看到了this并试图复制它,
class Coordinator : NSObject {
func webView(_ webView: WKWebView, js : String) {
webView.evaluateJavaScript(js)
}
}
但我无法让它工作。
提前致谢。
你可以在navigation delegate中试试,加载完成后,如下图:
class Coordinator : NSObject, WKNavigationDelegate {
// ... any other code
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript(js, completionHandler: { (value, error) in
// .. do anything needed with result, if any
})
}
}
struct WebView : UIViewRepresentable {
var url : URL;
func makeUIView(context: Context) -> WKWebView {
let webview = WKWebView()
webview.navigationDelegate = context.coordinator
return webview
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
func updateUIView(_ uiView: UIViewType, context: Context) {
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}
如何将 SwiftUI WebKit 视图的文本大小设置为 @State 变量?我有这段代码可以让我在 SwiftUI
中使用 WebViewsimport SwiftUI
import WebKit
struct WebView : UIViewRepresentable {
var url : URL;
func makeUIView(context: Context) -> WKWebView {
return WKWebView();
}
func updateUIView(_ uiView: UIViewType, context: Context) {
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}
我看到了this并试图复制它,
class Coordinator : NSObject {
func webView(_ webView: WKWebView, js : String) {
webView.evaluateJavaScript(js)
}
}
但我无法让它工作。
提前致谢。
你可以在navigation delegate中试试,加载完成后,如下图:
class Coordinator : NSObject, WKNavigationDelegate {
// ... any other code
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript(js, completionHandler: { (value, error) in
// .. do anything needed with result, if any
})
}
}
struct WebView : UIViewRepresentable {
var url : URL;
func makeUIView(context: Context) -> WKWebView {
let webview = WKWebView()
webview.navigationDelegate = context.coordinator
return webview
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
func updateUIView(_ uiView: UIViewType, context: Context) {
uiView.loadFileURL(url, allowingReadAccessTo: url)
}
}