Swift - Apply local css to web view

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.

Tags:

Css

Ios

Swift