将加载栏添加到WKWebView并选择其颜色

时间:2018-11-05 03:05:43

标签: ios swift xcode wkwebview

我正在尝试在WebView页面顶部添加加载栏。我在哪里添加代码。还可以更改此加载栏的颜色吗?enter image description here

    class CycleViewController: UIViewController, WKUIDelegate {

    var window: UIWindow?
    var webView: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.uiDelegate = self
        view = webView

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        webView.backgroundColor = UIColor.clear
        webView.backgroundColor = UIColor(red: 0.0196, green: 0.4, blue: 0.2902, alpha: 1.0)

        webView.isOpaque = false
        let myURL = URL(string: "https://jwelsh19.wixsite.com/countryday")
        let myRequest = URLRequest(url: myURL!)
        webView.load(myRequest)

    }
}

1 个答案:

答案 0 :(得分:2)

如果您不想要自定义视图,则可以使用SFSafariViewController来实现。使用以下代码

if let url = URL(string: "https://jwelsh19.wixsite.com/countryday") {
    let config = SFSafariViewController.Configuration()
    config.entersReaderIfAvailable = true

    let vc = SFSafariViewController(url: url, configuration: config)
    present(vc, animated: true)
}

如果您不想使用SFSafariViewController,则将uiprogress栏添加到webview容器视图中,观察webview的进度并相应地更新UIProgressbar 为了观察webview进度,请使用webview进度观察器

    webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress" {
            progressView.progress = Float(webView.estimatedProgress)
        }
    }