我正在尝试将
NSProgressIndicator
绑定到 Progress
,但是使用以下代码,即使在两个计时器触发之后,我也只能得到一个不确定的进度指示器,其中蓝色条永远左右弹跳。根据文档:
当totalUnitCount或completedUnitCount的值小于零或者两个值都为零时,进度是不确定的。 我做错了什么?
class ViewController: NSViewController {
let progress = Progress()
override func loadView() {
view = NSView(frame: CGRect(x: 0, y: 0, width: 500, height: 500))
let progressIndicator = NSProgressIndicator(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
progressIndicator.bind(.isIndeterminate, to: progress, withKeyPath: "isIndeterminate")
progressIndicator.bind(.value, to: progress, withKeyPath: "completedUnitCount")
progressIndicator.bind(.maxValue, to: progress, withKeyPath: "totalUnitCount")
progressIndicator.startAnimation(nil)
view.addSubview(progressIndicator)
progress.completedUnitCount = 3
progress.totalUnitCount = 10
Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
print(1)
self.progress.completedUnitCount = 6
}
Timer.scheduledTimer(withTimeInterval: 6, repeats: false) { _ in
print(2)
self.progress.completedUnitCount = 0
self.progress.totalUnitCount = 0
}
}
}
Cocoa Bindings 使用 Objective-C,Objective-C 属性的名称是
indeterminate
。使用 #keyPath
字符串表达式来获取正确的关键路径。
progressIndicator.bind(.isIndeterminate, to: progress, withKeyPath: #keyPath(NSProgressIndicator.isIndeterminate))