加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift:如何使用NSProgressIndicator?

发布时间:2020-12-14 04:42:39 所属栏目:百科 来源:网络整理
导读:我想使用NSProgressIndicator来显示一些进展.但我找不到一种方法来增加控制的范围.我也没有在网上找到一个例子. let progressbar = NSProgressIndicator()progressbar.frame = NSRect(x: 100,y: 20,width: 150,height: 10)progressbar.minValue = 0progressb
我想使用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秒间隔.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读