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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With