" I have taken " /> " I have taken " /> " I have taken "/>

Why WebKit font vs iOS UILabel has different Font?

56 views Asked by At

I am using webview & for changing font(size 50) of WKWebKit i am using

let fontSetting = "<span style=\"font-size: \(fontSize)\"</span>"

I have taken UILabel from storyboard of font-size 50

Why both size shows different ?

enter image description here My complete code is below ---

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
    }

}
1

There are 1 answers

1
Fahim Parkar On

This is because UILabel took default font (means font is assigned) however for web, you didn't specify font name.

Check below code which is working fine at my end.

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)
    
}

In localization I have

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

AppsColor have below

static let color_000000 : String = "#000000"