Pjo*_*trC 6 nsprogressindicator swift
我想使用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
}
Run Code Online (Sandbox Code Playgroud)
您将无法在如此紧凑的循环中演示进度条.
当您设置进度指示器的值时,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)
})
}
}
}
Run Code Online (Sandbox Code Playgroud)
这使得呼叫incrementBy(1)以1秒的间隔排队.
| 归档时间: |
|
| 查看次数: |
6837 次 |
| 最近记录: |