Swift - 将本地css应用于Web视图 [英] Swift - Apply local css to web view
本文介绍了Swift - 将本地css应用于Web视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在网页视图中加载一个html页面,我想应用一个本地css文件。
我从服务器接收字符串中的html,而css将在我的应用程序中。例如,我想显示你好!红色的。
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)
你知道怎么申请css吗?
我应该尝试使用WKWebView吗?
Do you know how to apply the css ? Should I try with a WKWebView ?
提前致谢。
推荐答案
添加 UIWebView的委托方法
就像这样
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);
}
}
希望这会对你有帮助。
这篇关于Swift - 将本地css应用于Web视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文