Injecting a new stylesheet into a website via uiwebview using iOS8 Swift XCode 6

后端 未结 2 627
难免孤独
难免孤独 2020-12-21 14:57

I\'ve seen a few options on here using just Objective-C, but I\'m having trouble doing this with Swift iOS8 in XCode 6. I\'m using the uiwebview to load a website. For sake

2条回答
  •  长情又很酷
    2020-12-21 15:27

    Using the now preferred WKWebView you can put the external css file, say tweaks.css in the root of your project or in a sub-folder, then you can inject it into your page like this:

    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 the file available:

    1. Click your project
    2. Click your target
    3. Select Build Phases
    4. Expand Copy Bundle Resources
    5. Click '+' and select your file.

    Also make sure that your controller implements WKNavigationDelegate:

    class ViewController: UIViewController, WKNavigationDelegate 
    

提交回复
热议问题