4
웹보기에서 HTML 페이지를로드하고 로컬 CSS 파일을 적용하려고합니다. 서버에서 문자열로 html을 받고 있는데 CSS가 내 앱에 있습니다. 예를 들어 여기서 "Hello!"라고 표시하려고합니다. 빨간색으로.Swift - 로컬 CSS를 웹보기에 적용
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를 사용해 볼까요?
미리 감사드립니다. 이 당신을 도울 것이
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);
}
}
희망 같은 UIWebView
의
작동하지 않습니다. 내 CSS에는 다음 줄만 있습니다.'h1, h2 {font-family : "--unknown-1--", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; color : # 94C11D}'. –
대답을 편집했습니다. 지금 확인하십시오. –
코드에 약간의 조정을했지만 작동합니다 !! 대단히 감사합니다 :) –