I load text to the WebView. And I need to change font and its size. I use this code, but font is too small. It isn't 15 points. What is my problem?
private lazy var webView: WKWebView = {
let contentController = WKUserContentController()
let webConfig = WKWebViewConfiguration()
webConfig.userContentController = contentController
webConfig.dataDetectorTypes = [.phoneNumber, .link]
let web = WKWebView(frame: .zero, configuration: webConfig)
web.navigationDelegate = self
return web
}()
...
let fontName = "PFHandbookPro-Regular"
let fontSize = 15
let fontSetting = "<span style=\"font-family: \(fontName);font-size: \(fontSize)\"</span>"
webView.loadHTMLString(fontSetting + myHTMLString, baseURL: nil)
The span
tag you have won't really do anything, since it's opening and closing immediately -- it doesn't contain any content.
This solution works assuming your HTML string doesn't already have full <head>
and <body>
tags:
let header = """
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
<style>
body {
font-family: "Avenir";
font-size: 24px;
}
</style>
</head>
<body>
"""
webView.loadHTMLString(header + myHTMLString + "</body>", baseURL: nil)
The first important thing this does is set the viewport so that the page is the correct scale for the device (the primary reason your text was so small). Then, it also shows you how to set a font family and font size for the body of the HTML.
If your HTML markup already has <head>
and <body>
tags, you might want to do the same sorts of things (changing the viewport and body styles) by injecting javascript. You can see some info about doing this here: WKWebView equivalent for UIWebView's scalesPageToFit
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.