Tuesday, December 12, 2023
HomeiOS Developmentswift - How can I dynamically change the font measurement of webview...

swift – How can I dynamically change the font measurement of webview in ios


struct WebView: UIViewRepresentable {
    @Binding var worth: Double
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(self, worth: $worth)
    }
    
    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(body: CGRect.zero, configuration: configuration)
        webView.navigationDelegate = context.coordinator
        
        guard let htmlURL = Bundle.foremost.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.foremost.url(forResource: "index", withExtension: "html") else { return }
        uiView.loadFileURL(htmlURL, allowingReadAccessTo: htmlURL.deletingLastPathComponent())
    }
    
    class Coordinator : NSObject, WKNavigationDelegate {
        var dad or mum: WebView
        @Binding var worth: Double
        
        init(_ uiWebView: WebView, worth: Binding<Double>) {
            self.dad or mum = uiWebView
            self._value = worth
        }
        
        func webView(_ webview: WKWebView,
                       didFinish: WKNavigation!) {
            webview.evaluateJavaScript("doc.physique.type.fontSize = "(Int(worth))px";")
        }
    }
}

Get HTML native, the display is being proven in webView. Each time the slider worth adjustments, I need to change the font measurement of webView via webview.valueJavaScript, however there are adjustments, which isn’t what I would like. Are you aware tips on how to clear up this downside?

func makeUIView(context: Context) -> WKWebView {
...
    let script = WKUserScript(supply: "doc.physique.type.fontSize = "(Int(worth))px";", injectionTime: .atDocumentEnd, forMainFrameOnly: true)
    contentController.addUserScript(script)
...
}

I attempted to alter the script by registering it, however the font measurement solely modified at first, but it surely did not change afterwards.



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments