Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Apply local css to web view

Tags:

css

ios

swift

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.

like image 757
Melanie Journe Avatar asked Jun 20 '16 12:06

Melanie Journe


2 Answers

Add delegate method of UIWebView like this

func webViewDidFinishLoad(webView: UIWebView) {    
    if let path = Bundle.main.path(forResource: "styles", ofType: "css") {
       let javaScriptStr = "var link = document.createElement('link'); link.href = '%@'; link.rel = 'stylesheet'; document.head.appendChild(link)"
       let javaScripthPath = String(format: javaScriptStr, path)
       self.articleView.stringByEvaluatingJavaScript(from: javaScripthPath)
    }

    //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.

like image 87
Nirav D Avatar answered Sep 30 '22 14:09

Nirav D


If you are loading CSS from external file or from multiline string, don't forget to replace occurrences of newline \n like this:

cssString.replacingOccurrences(of: "\n", with: "")

Without this innerHtml will not work (because it don't know \n so it's not valid) and show you an error.

like image 44
Boomerange Avatar answered Sep 30 '22 12:09

Boomerange