Melanie Journe Melanie Journe - 5 months ago 69
Swift Question

Swift - Apply local css to web view

I'm loading a html page in a web view and I want to apply a local css file.
I'm receiving the html in a string from a server and the css will be in my app. For example here I want to display "Hello!" in red.

self.articleView = UIWebView(frame : CGRect(x : self.articleButton.frame.minX, y : self.articleButton.frame.maxY + 1, width : self.frame.width - 20, height: self.frame.height - self.articleButton.frame.maxY - 10));
self.articleView.backgroundColor = UIColor.clearColor();
self.addSubview(self.articleView);
self.articleView.loadHTMLString("<html><body><h1>Hello!</h1></body></html>", baseURL: nil)


Do you know how to apply the css ?
Should I try with a WKWebView ?

Thanks in advance.

Answer

Add delegate method of UIWebView like this

func webViewDidFinishLoad(webView: UIWebView) {    
    let path = NSBundle.mainBundle().pathForResource("styles", ofType: "css")
    let javaScriptStr = "var link = document.createElement('link'); link.href = '%@'; link.rel = 'stylesheet'; document.head.appendChild(link)"
    let javaScripthPath = NSString(format: javaScriptStr, path!)
    webView.stringByEvaluatingJavaScriptFromString(javaScripthPath as String)

    //Second way
    do {
        let cssContent = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding as NSStringEncoding);
        let javaScrStr = "var style = document.createElement('style'); style.innerHTML = '%@'; document.head.appendChild(style)"
        let JavaScrWithCSS = NSString(format: javaScrStr, cssContent)
        self.articleView.stringByEvaluatingJavaScriptFromString(JavaScrWithCSS as String)

    }
    catch let error as NSError {
        print(error);
    }
}

Hope this will help you.

Comments