Swift & UIWebView element to hide

半腔热情 提交于 2019-12-13 15:26:39

问题


I got a UIWebView and I load the content like that

let url = NSURL (string: "http://www.myresponsivesite.fr/section/");
    let requestObj = NSURLRequest(URL: url!);
    webView.loadRequest(requestObj);

It's working perfectly but I would like to put some div and other elements in display none. So my question is : How can I inject some css from my app with swift? Thanks.


回答1:


I finally found another way, I load my html in a variable and, i replace some div with a "display:none" exemple :

 let urlDeBase = "http://mywebsite/section/"    
    if let url = NSURL (string: urlDeBase){
        var error: NSError?
        let myHTML = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)

and I replace what i want

 let mystring = myHTML?.stringByReplacingOccurrencesOfString("<h3 class=\"myclass\">Menu</h3>", withString: "<h3 class=\"myclass\" style=\"display:none\">Menu</h3>")
 webvieww.loadHTMLString(mystring, baseURL: nil)



回答2:


I found a couple post on it and the Apple docs, here was one solution:

So, I think I found at least one way to accomplish appending styles to the webpage being loaded using Swift:

var loadStyles = "var script = 
  document.createElement('link');
  script.type = 'text/css';
  script.rel = 'stylesheet';
  script.href = 'http://fake-url/styles.css';
  document.getElementsByTagName('body')[0].appendChild(script);"

website.stringByEvaluatingJavaScriptFromString(loadStyles)

Here is the other post: Swift stringByEvaluatingJavaScriptFromString

Then the Apple docs.



来源:https://stackoverflow.com/questions/32355912/swift-uiwebview-element-to-hide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!