Search code examples
macoscocoanssegmentedcontrol

Keyboard Shortcuts for NSSegmentedControl Button in COCOA Mac Application


In my COCOA Mac Application, there is one NSSegmentedControl Button for Queue ON/OFF functionality. Now I need to provide keyboard shortcut for the same. For example, for Queue ON if already it was Off and vice versa.

Is anyone did this type of functionality?

Thanks and Regards, Barun


Solution

  • Since I didn't find a way to add a keyboard binding to the NSSegmentedControl via interface builder, I did id programmatically. I created a custom Window class named PMWindow:

    @implementation PMWindow
    
    - (BOOL)acceptsFirstResponder {
        return YES;
    }
    
    - (void)keyDown:(NSEvent *)theEvent {
        if([self.viewController.lastNextControl isEnabled]) {
            if([theEvent keyCode] == 123) {
                [self.viewController last];
            } else if([theEvent keyCode] == 124) {
                [self.viewController next];
            }
        }
    }
    
    @end
    

    I added my view controller named PMViewController via the interface builder to the Window class PMWindow. In this example I'm reacting to the key strokes < left arrow > (123) and < right arrow > (124).

    For completeness of this example I added here the implementation of the method which gets called when somebody hits a cell of my NSSegmentedControl element:

    - (IBAction)lastOrNext:(id)sender {
        switch ([sender selectedSegment]) {
            case 0:
                [self last];
                break;
            case 1:
                [self next];
                break;
        }
    }