Embed a new stylesheet in a website via uiwebview using iOS8 Swift Xcode 6

I saw several options here using only Objective-C, but I am having problems with this with Swift iOS8 in Xcode 6. I use uiwebview to load the website. For example, let's say its google.com.

@IBOutlet var website: UIWebView! var url = "http://www.google.com" func loadUrl() { let requestURL = NSURL(string: url) let request = NSURLRequest(URL: requestURL!) website.loadRequest(request) } override func viewDidLoad() { super.viewDidLoad() website.delegate = self loadUrl() } func webViewDidFinishLoad(website: UIWebView) { var jsscript = "some script here" website.stringByEvaluatingJavaScriptFromString(jsscript) } 

Using Swift, how would I introduce a new stylesheet to a site to overwrite many styles?

In addition, I would like the new stylesheet to exist in one of my application directories. Where is the best directory for this? In the "File Support?" And how would I name this path in my code?

It would be nice if the site did not load until the styles were applied.

+2
source share
2 answers

So, I think that I have found at least one way to add styles to a web page loaded with 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) 
+4
source

Using now the preferred WKWebView, you can put the external css file, say tweaks.css in the root of your project or in a subfolder, then you can enter it on your page as follows:

 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { guard let path = Bundle.main.path(forResource: "tweaks", ofType: "css") else { return } let css = try! String(contentsOfFile: path).replacingOccurrences(of: "\\n", with: "", options: .regularExpression) let js = "var style = document.createElement('style'); style.innerHTML = '\(css)'; document.head.appendChild(style);" webView.evaluateJavaScript(js) } 

To make a file available:

  • Click on your project.
  • Choose a target
  • Assembly phase selection
  • Expand Copy Resources
  • Press "+" and select a file.

Also make sure your controller implements WKNavigationDelegate:

 class ViewController: UIViewController, WKNavigationDelegate 
0
source

Source: https://habr.com/ru/post/893861/


All Articles