7

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.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.