Determine when NSSlider knob is 'let go' in continuous mode
Took me a little while to find this thread, but the accepted answer (although old) is great for detecting NSSlider state changes (slider value stopped changing being the main one I was looking for)!
Answer in Swift (Swift 4.1):
let slider = NSSlider(value: 1,
minValue: 0,
maxValue: 4,
target: self,
action: #selector(sliderValueChanged(sender:)))
. . .
@objc func sliderValueChanged(sender: Any) {
guard let slider = sender as? NSSlider,
let event = NSApplication.shared.currentEvent else { return }
switch event.type {
case .leftMouseDown, .rightMouseDown:
print("slider value started changing")
case .leftMouseUp, .rightMouseUp:
print("slider value stopped changing: \(slider.doubleValue)")
case .leftMouseDragged, .rightMouseDragged:
print("slider value changed: \(slider.doubleValue)")
default:
break
}
}
Note: the right event types account for someone who has reversed their mouse buttons ð¤.
You could also simply check the type of the current event in the action method:
- (IBAction)sliderChanged:(id)sender
{
NSEvent *currentEvent = [[sender window] currentEvent];
if ([currentEvent type] == NSLeftMouseUp) {
// the slider was let go
}
}
This works for me (and is easier than subclassing NSSlider):
- (IBAction)sizeSliderValueChanged:(id)sender {
NSEvent *event = [[NSApplication sharedApplication] currentEvent];
BOOL startingDrag = event.type == NSLeftMouseDown;
BOOL endingDrag = event.type == NSLeftMouseUp;
BOOL dragging = event.type == NSLeftMouseDragged;
NSAssert(startingDrag || endingDrag || dragging, @"unexpected event type caused slider change: %@", event);
if (startingDrag) {
NSLog(@"slider value started changing");
// do whatever needs to be done when the slider starts changing
}
// do whatever needs to be done for "uncommitted" changes
NSLog(@"slider value: %f", [sender doubleValue]);
if (endingDrag) {
NSLog(@"slider value stopped changing");
// do whatever needs to be done when the slider stops changing
}
}