进度栏在可可 [英] Progress Bar in Cocoa

查看:161
本文介绍了进度栏在可可的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的应用程序包含一个WebView。此网页视图加载了HTML5应用,并且在网页视图内部构建内容时需要一些时间。

I have a very simple application that contains a WebView. This webview loads an HTML5 app and it takes some time while the content is being built inside the webview.

我想显示一个进度条,直到内容完成加载,并在内容准备就绪后显示webview。大约需要10秒钟。

I would like to show a progress bar until the content finishes loading and show the webview when the content is ready. It takes roughly 10 seconds.

推荐答案

Swift 2.2



Swift 2.2

override func viewDidLoad() {
    super.viewDidLoad()

    webView.frameLoadDelegate = self
    webView.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil) // add observer for key path
}

/// Observer listening for progress changes
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    if (keyPath == "estimatedProgress") { // listen to changes and updated view
        if self.webView.estimatedProgress == 0 { return }
        // All UI operations always in main thread
        dispatch_async(dispatch_get_main_queue(), {
            // *100 because progressIndicator in Mac OS wants values from 0 to 100
            self.progressIndicator.doubleValue = self.webView.estimatedProgress * 100
        })
    }
}

/// Hide progress indicator on finish
func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!) {
    dispatch_async(dispatch_get_main_queue(), { self.progressIndicator.hidden = true })
}

/// Show progress indicator on start page loading
func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!) {
    dispatch_async(dispatch_get_main_queue(), { self.progressIndicator.hidden = false })
}



Swift 3



Swift 3

override func viewWillAppear() {
    super.viewWillAppear()
    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") { // listen to changes and updated view
        DispatchQueue.main.async {
            // Here you can do set your actions on progress update
            // E.g.: someProgressBar.doubleValue = self.webView.estimatedProgress * 100
        }
    }
}

override func viewWillDisappear() {
    super.viewWillDisappear()
    webView.removeObserver(self, forKeyPath: "estimatedProgress")
}



完整解决方案



我创建了 Swift 3 Cocoa代码片段与NSViewController嵌入WKWebViewController和NSProgressIndicator,所以你可以看看实例。

Full solution

I've created Swift 3 Cocoa code snippet with NSViewController with embedded WKWebViewController and NSProgressIndicator so you can look at live example.

这篇关于进度栏在可可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆