Determine when NSSlider knob is 'let go' in continuous mode

后端 未结 7 1117
青春惊慌失措
青春惊慌失措 2020-12-17 10:19

I\'m using an NSSlider control, and I\'ve configured it to use continuous mode so that I can continually update an NSTextField with the current value of the slider while the

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-17 10:26

    Just found an elegant way to have a slider continuously updating a label, and storing the slider's value only when the user releases all the mouse buttons.

    class YourViewController: NSViewController {
        @IBOutlet weak var slider: NSSlider!
        @IBOutlet weak var label: NSTextField!
    
        @objc var sliderValue = 0
    
        override func awakeFromNib() {
            sliderValue = 123 // init the value to whatever you like
    
            slider.bind(NSBindingName("value"), to: self, withKeyPath: "sliderValue")
            label.bind(NSBindingName("value"),  to: self, withKeyPath: "sliderValue")
        }
    
        @IBAction func sliderMoved(_ sender: NSSlider) {
            // return if a mouse button is pressed
            guard NSEvent.pressedMouseButtons == 0 else { return }
    
            // do something with the value
        }
    }
    

提交回复
热议问题