The font looks like smaller in WKWebView than in U

2020-05-14 16:14发布

问题:

I changed UIWebView to WKWebView,however,with the same html,the font in WKWebView looks like smaller than in UIWebView.I don't want this happen,so is there any way to avoid this change?

回答1:

Finally I solved this problem by adding an html string:

  • For Objective-C:
NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";
[self.webView loadHTMLString:[headerString stringByAppendingString:yourHTMLString] baseURL:nil];
  • For Swift:
let headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>"
webView.loadHTMLString(headerString + yourHTMLString, baseURL: nil)

What's more,if you want to load url rather than html you can try:

private var isInjected: Bool = false
webView.navigationDelegate = self
// MARK: - WKNavigationDelegate
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    if isInjected == true {
        return
    }
    self.isInjected = true
    // get HTML text
    let js = "document.body.outerHTML"
    webView.evaluateJavaScript(js) { (html, error) in
        let headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>"
        webView.loadHTMLString(headerString + (html as! String), baseURL: nil)
    }

}


回答2:

let description = "<p> HTML content <p>"
var headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0'></header>"
headerString.append(description)              
self.webView.loadHTMLString("\(headerString)", baseURL: nil)


回答3:

Simple way to do this in Swift

extension WKWebView {

    /// load HTML String same font like the UIWebview
    ///
    //// - Parameters:
    ///   - content: HTML content which we need to load in the webview.
    ///   - baseURL: Content base url. It is optional.
    func loadHTMLStringWithMagic(content:String,baseURL:URL?){
        let headerString = "<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>"
        loadHTMLString(headerString + content, baseURL: baseURL)
    }
}

Just simply call this method and magic happen. ;)

webView.loadHTMLStringWithMagic(content: "<p> HTML content <p>", baseURL: nil)

OUTPUT: