Short Note: Performing actions on certain events with a continuous state NSSlider (Swift 3 / Xcode 8.x)

Short Note: Performing actions on certain events with a continuous state NSSlider (Swift 3 / Xcode 8.x)

This took me a while, because Apple documentation is horribly outdated and incomplete regarding Cocoa and Swift, to say the least.

Background

If you need an NSSlider that sends its current value continuously to keep e.g. a label or some other UI elements in sync while the user is dragging the slider’s knob, you set the state of the slider element to continuous. However, by doing so, you cannot detect easily, if the user has stopped interaction with the slider, anymore. On the other hand, if you disable the continuous state, you will only receive updates on every end of an interaction i.e. if the user releases the left mouse button.

Desired behavior

If you want to have information in both situations, consider the following solution:

@IBOutlet weak var mySlider: NSSlider!

...

@IBAction func handlingNSSliderChanges(_ sender: Any) {
        
    // Perform updates on certain events
    if sender is NSSlider{
        let event = NSApplication.shared().currentEvent
            
        if event?.type == NSEventType.leftMouseUp {
            print("LeftMouseUp event inside continuous state NSSlider")
        }
    }

    // Do continuous updates
    if let value = mySlider?.integerValue{
        demoLabel.stringValue = String(value)
    }
}

...

Note: No function override, class extensions nor subclassing needed! Yay!

Tags: , , , ,

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert