cocoaappkitnsprogressindicator

NSProgressIndicator bindings don't do anything


I'm trying to bind a NSProgressIndicator to Progress, but with the following code I only get an indeterminate progress indicator with a blue bar forever bouncing left and right, even after the two timers fire. According to the documentation:

Progress is indeterminate when the value of the totalUnitCount or completedUnitCount is less than zero or if both values are zero. What am I doing wrong?

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
        }
    }

}

Solution

  • Cocoa Bindings use Objective-C and the name of the Objective-C property is indeterminate. Use the #keyPath string expression to get the correct key path.

    progressIndicator.bind(.isIndeterminate, to: progress, withKeyPath: #keyPath(NSProgress.isIndeterminate))