Vanya Vanya - 7 months ago 36
iOS Question

How to change UIWebView font by using JavaScript?

I am wondering how to change font by using JavaScript.

While this:

let fontName = "AmericanTypewriter-CondensedBold"

if let infoString = config.textAboutApplication {
infoView.loadHTMLString(NSString(format: "<div style='text-align:left;font-family:%@'>%@<div>", fontName, infoString) as String, baseURL: nil)

produces proper outcome with formatted text, JavaScript version does not:

func webViewDidFinishLoad(webView: UIWebView)
let fontName = "AmericanTypewriter-CondensedBold"

let jsString = NSString(format: "document.getElementById('p').style.fontFamily = '%@'", fontName)
webView.stringByEvaluatingJavaScriptFromString(jsString as String)

The HTML text does have
tag and text inside, so I am doing something wrong regarding the JavaScript part probably.


Ok I was trying thing around, JavaScript is not my strongest thing, and this works

let fontName = "AmericanTypewriter-CondensedBold"

    let jsString =  NSString(format: "document.getElementsByTagName('p')[0].style.fontFamily = '%@'", fontName)
    let js = webView.stringByEvaluatingJavaScriptFromString(jsString as String)

EDIT: I did custom implementation regarding this messy solution to be swifty cool. :)