为什么WebKit字体与iOS UILabel有不同的字体?

zwghvu4y  于 2023-06-07  发布在  iOS
关注(0)|答案(1)|浏览(215)

我正在使用webview &用于更改我正在使用的WKWebKit的字体(大小50)
let fontSetting = "<span style=\"font-size: \(fontSize)\"</span>"
我从字体大小为50的故事板中获取了UILabel
为什么两种尺寸显示不同?
x1c 0d1x我的完整代码如下---

import UIKit
import WebKit

class ViewController: UIViewController {
    var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView = WKWebView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 200))
        webView.navigationDelegate = self
        view.addSubview(webView)
    }
    

    override func viewDidAppear(_ animated: Bool) {
        let htmlStr = """
        <p><a href="https://www.google.com">WebView-Button-size-50</a></p>
        """
        let fontSize = 50
        let fontSetting = "<span style=\"font-size: \(fontSize)\"</span>"
        webView.loadHTMLString(fontSetting + htmlStr, baseURL: nil)
        webView.allowsBackForwardNavigationGestures = true
    }

}
ftf50wuq

ftf50wuq1#

这是因为UILabel采用了默认字体(意味着字体已分配),但对于Web,您没有指定字体名称。
检查下面的代码,这是工作正常在我的结束。

func adjustHTMLData(htmlText : String) {
    let innerFontName: String = "myFontName".localized()
    
    let innerFontSize1: CGFloat = 32*iPhoneFactorX
    let innerDirection: String = "myDir".localized()
    
    var  header002: String = htmlText
    header002 = header002.replacingOccurrences(of: "font-family", with: "f ont-family")
    header002 = header002.replacingOccurrences(of: "<font", with: "<ffont")
    
    let htmlString: String = "<html><head><style type='text/css'>body {background-color: transparent;border: 0px;margin: 10px;padding: 0px;font-family: '\(innerFontName)'; font-size: \(innerFontSize1)px;color:\(AppColors.color_000000);}</style></head><body dir='\(innerDirection)'>\(header002)<br /><br /><style>@font-face {font-family: '\(innerFontName)';font-weight: normal;src: url(\("fontTTF".localized()));}</style><style type='text/css'> iframe { width: 100%% !important; } img {width: 100% !important; height: auto;} a {text-decoration: none; color : \(AppColors.color_000000)} table {width: 100%% !important;} }</style></body></html>";
    
    print("htmlString==\(htmlString)")
    self.myWebview.loadHTMLString(htmlString, baseURL: Bundle.main.bundleURL)
    
}

在本地化方面,我有

"fontTTF"="Poppins-Regular.ttf";
"myFontName"="Poppins-Regular";
"myDir"="LTR";

AppsColor在下面

static let color_000000 : String = "#000000"

相关问题