在 WKWebView 中将 EstimatedProgress/ProgressView 变成进度条

Turning EstimatedProgress/ProgressView into progress bar in WKWebView

我在弄清楚如何获取 ProgressView 时遇到问题,我已将其转换为可以看到的 UI 进度条的估计进度。在我的输出中,我可以清楚地看到它正在跟踪数据,但是当测试为 运行 时,UI 上没有显示任何内容。我想在我的导航栏底部添加一个进度条。

class CycleViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {

@IBOutlet var webView: WKWebView!
@IBOutlet var progressView: UIProgressView!

override func loadView() {
    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.applicationNameForUserAgent = "Version/8.0.2 Safari/600.2.5"
    webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.uiDelegate = self
    view = webView

    progressView = UIProgressView(progressViewStyle: .default)
    progressView.sizeToFit()
    progressView.progressTintColor = UIColor(red: 255/255, green: 204/255, blue: 0/255, alpha: 1.0)

}

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

    self.webView.load(NSURLRequest(url: URL(string: "https://jwelsh19.wixsite.com/countryday")!) as URLRequest);

    self.webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil);
}

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

}

viewDidLoad( ) 在视图加载完成时调用,而 loadView( ) 在视图开始加载时调用。 将此代码移至 ViewDidLoad

//progressView = UIProgressView(progressViewStyle: .default) // remove this line
progressView.sizeToFit()
progressView.progressTintColor = UIColor(red: 255/255, green: 204/255, blue: 0/255, alpha: 1.0)

也不需要重新创建网络视图。只需从情节提要中删除 webview 并以编程方式创建它并使用容器视图设置他的约束。在情节提要中添加容器视图,从进度条开始到 viewcontroller 底部。在容器视图中添加您的 webview。我检查了您的代码并更新了修复程序。 Download code

你好像在 xib 的视图上添加了进度条。但是,您还将 loadView() 中的此视图替换为 WKWebView,这似乎是进度条变为零的原因。

作为一般规则,Apple 对 loadView() 方法声明如下:

This method connects an instantiated view from a nib file to the view property of the view controller. This method is called by the system, and is exposed in this class so you can override it to add behavior immediately before or after nib loading.

Do not call this method. If you require this method to be called, access the view property.

Do not invoke this method from other objects unless you take care to avoid redundant invocations.

对于您的情况,您可以考虑以下任一方法而不是对 loadView() 执行初始化:

  1. webView 的初始化放在 viewDidLoad() 中,然后将两者都添加 webViewprogressView 作为视图
  2. 的子视图
  3. 或者,你也可以在 xib 中添加 webView 这样你 不需要调用 view = webView 并移动额外的 webViewprogressView 配置改为 viewDidLoad()