struct WebView: UIViewRepresentable {
@Binding var value: Double
func makeCoordinator() -> Coordinator {
return Coordinator(self, value: $value)
}
func makeUIView(context: Context) -> WKWebView {
let contentController = WKUserContentController()
let preferences = WKWebpagePreferences()
preferences.allowsContentJavaScript = true
let configuration = WKWebViewConfiguration()
configuration.userContentController = contentController
configuration.defaultWebpagePreferences = preferences
configuration.processPool = WKProcessPool()
let webView = WKWebView(frame: CGRect.zero, configuration: configuration)
webView.navigationDelegate = context.coordinator
guard let htmlURL = Bundle.main.url(forResource: "index", withExtension: "html") else { return WKWebView() }
webView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL.deletingLastPathComponent())
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {
guard let htmlURL = Bundle.main.url(forResource: "index", withExtension: "html") else { return }
uiView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL.deletingLastPathComponent())
}
class Coordinator : NSObject, WKNavigationDelegate {
var parent: WebView
@Binding var value: Double
init(_ uiWebView: WebView, value: Binding<Double>) {
self.parent = uiWebView
self._value = value
}
func webView(_ webview: WKWebView,
didFinish: WKNavigation!) {
webview.evaluateJavaScript("document.body.style.fontSize = \"\(Int(value))px\";")
}
}
}
Get HTML local, the screen is being shown in webView. Whenever the slider value changes, I want to change the font size of webView through webview.valueJavaScript, but there are changes, which is not what I want. Do you know how to solve this problem?
func makeUIView(context: Context) -> WKWebView {
...
let script = WKUserScript(source: "document.body.style.fontSize = "\(Int(value))px";", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
contentController.addUserScript(script)
...
}
I tried to change the script by registering it, but the font size only changed at first, but it didn’t change afterwards.




