【问题标题】:How to Insert CSS from a URL in WKWebView though HTML content from URL is loaded successfully尽管成功加载了来自 URL 的 HTML 内容,如何在 WKWebView 中从 URL 插入 CSS
【发布时间】:2018-10-30 07:30:09
【问题描述】:

我搜索并发现了许多帖子,我从中获得了从捆绑包或字符串加载 CSS 文件的解决方案。但是我的 CSS 文件保存在我们的服务器上。 我想从 URL 加载 CSS。我尝试了很多方法,但它对我不起作用。 尽管我可以在 Objective C 代码中的 UIWebView 中从相同的 URL 插入 CSS,但我在尝试在 SWIFT 的 WKWebView 中实现相同的目标时遇到了问题。我想我在编写 HTML 标记时犯了一些语法错误。请帮帮我

这是Objective C的代码:

NSString *html = [NSString stringWithFormat:@"<link type=\"text/css\" href=\"%@\" rel=\"stylesheet\" /> %@<br>", htmlData.cssStr,[htmlData.contentsArr objectAtIndex:slideNo]];
NSLog(@"html .%@", html);
[webview loadHTMLString:html baseURL:nil];

htmlData.cssStr : 这是一个网络链接

与大多数解决方案一样,CSS 在 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) 中插入 SWIFT。所以我也从 WKWebView 的 didFinish 中调用 insertContentsOfCSSFile。 我在 SWIFT 中的尝试是:

func insertContentsOfCSSFile(into webView: WKWebView) {

    let cssString = try! String(contentsOf: URL(string:  self.htmlData.cssStr)!).trimmingCharacters(in: .whitespacesAndNewlines)
    print("cssString", cssString)
    let jsString = "var style = document.createElement('style'); style.innerHTML = '\(cssString)'; document.head.appendChild(style);"
        webView.evaluateJavaScript(jsString, completionHandler: nil)

}

【问题讨论】:

    标签: objective-c swift4 wkwebview


    【解决方案1】:

    在您的 HTML 中,您需要 HTML、Head、Body 等父标签。请尝试以下代码。以及您希望的更改。

    NSString *bodyTag = [NSString stringWithFormat:@"<body><div id='main-div'>%@</div></body>",[htmlData.contentsArr objectAtIndex:slideNo]]; // Pass Var -> body value
    NSString *css = [NSString stringWithFormat:@"<link type=\"text/css\" href=\"%@\" rel=\"stylesheet\" />", htmlData.cssStr];
    
    NSString *htmlString = [NSString stringWithFormat:@"<!DOCTYPE html><html xmlns='https://www.w3.org/1999/xhtml'><head>  <meta http-equiv='Content-Type' content='text/html; charset=utf-8' /><meta name = \"viewport\" content = \"width = 320, initial-scale = 1.0, user-scalable = yes\"><link href=\"%@\" rel=\"stylesheet\" type=\"text/css\" /></head>%@</html>", css, bodyTag]; // Pass Var -> css url and bodyTag 
    

    【讨论】:

    • 我可以让它在 Objective C 中工作,但我需要用 SWIFT 语言编写。
    猜你喜欢
    • 2016-01-12
    • 2018-01-21
    • 1970-01-01
    • 2019-08-22
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2020-11-14
    • 2016-07-19
    相关资源
    最近更新 更多