Swift:如何使用 NSProgressIndicator?

标签 swift nsprogressindicator

我想使用 NSProgressIndicator 来显示一些进度。但我找不到增加该控制栏的方法。我也没有在网上找到示例。

let progressbar = NSProgressIndicator()
progressbar.frame = NSRect(x: 100, y: 20, width: 150, height: 10)
progressbar.minValue = 0
progressbar.maxValue = 10
self.window.contentView?.addSubview(progressbar)

for i in 0...10 {
    progressbar.incrementBy(1)  //has no effect
}

最佳答案

您将无法在如此紧凑的循环中演示进度条。

当您设置进度指示器的值时,OS X 显示机制直到下一次通过事件循环时才实际绘制差异,这直到您的方法返回后才会发生。换句话说,在进度指示器甚至有机会重绘自身之前,您将其一直设置为 10,因此您所看到的只是最终填充状态。

理论上您可以在每次循环后强制显示进度指示器 (progressbar.display()),但我认为您无法区分它们之间的差异发生在 0.01 秒内。

然后,解决方案是在调用 incrementBy(1) 之间引入一个小的延迟,以便可以发生下一个事件循环并显示新值。您可以通过在代码中添加类似以下的内容来实现:

func delay(delay:Double, closure:()->()) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW,
        Int64(delay * Double(NSEC_PER_SEC))),
                   dispatch_get_main_queue(), closure)
}

class AppDelegate: NSObject, NSApplicationDelegate {
    @IBOutlet weak var progressIndicator: NSProgressIndicator!

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        let progressbar = NSProgressIndicator()
        progressbar.frame = NSRect(x:100, y:20, width:150, height:10)
        progressbar.minValue = 0
        progressbar.maxValue = 10
        self.window.contentView?.addSubview(progressbar)

        self.progressIndicator = progressbar
        progressIndicator.indeterminate = false

        for i in 0...10 {
            delay(1.0 * Double(i), closure: { 
                self.progressIndicator.incrementBy(1)
            })
        }
    }
}

这会将 incrementBy(1) 的调用排队,间隔为 1 秒。

关于Swift:如何使用 NSProgressIndicator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38212874/

相关文章:

swift - swift 中 forEach 循环的进度条

cocoa - 将 NSTimer 链接到 NSProgressIndicator

macos - NSProgressIndicator 每当开始动画时就会消失

ios - 将特定类型的数据显示到 TableView

swift - 等效的 Swift NSURLSession 或 Alamofire Curl 帖子

ios - 试图从我局域网中的 NAS 服务器检索目录列表

objective-c - 不确定的 NSProgressIndicator 不会设置动画

cocoa - NSTableView + NSProgressIndicator 闪烁问题

ios - 正在取消 Alamofire 请求

ios - pageViewController viewControllerAfter/Before dataSource 方法被调用两次