Swift & UIWebView element to hide

2019-07-08 08:18发布

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.

2条回答
不美不萌又怎样
2楼-- · 2019-07-08 08:28

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)
查看更多
你好瞎i
3楼-- · 2019-07-08 08:44

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.

查看更多
登录 后发表回答