Rubber Duck
Rubber Duck

Reputation: 3037

Keyboard Events Objective C

I'm having trouble receiving keyboard events within a subclass of NSView.

I can handle mouse events fine, but my keyDown and keyUp methods are never called. It was my understanding per the documentation that both types of events follow the same hierarchy, however this is seemingly not the case.

Is this a first responder issue? Some field somewhere grabbing the focus? I've tried overriding that but no luck.

Any insights would be greatly appreciated.

If you'd like to see.. this is within a custom NSView class:

#pragma mark -
#pragma mark I/O Events
-(void)keyDown:(NSEvent *)theEvent {
    NSLog(@"Sup brah!");
}

-(void)keyUp:(NSEvent *)theEvent {
    NSLog(@"HERE");
}

// This function works great:
-(void)mouseDown:(NSEvent *)theEvent {
    NSNumber *yeah = [[NSNumber alloc] initWithBool:YES];
    NSNumber *nah = [[NSNumber alloc] initWithBool:NO];
    NSString *asf = [[NSString alloc] initWithFormat:@"%@", [qcView valueForOutputKey:@"Food_Out"]];

    if ([asf isEqualToString:@"1"]) {
        [qcView setValue:nah forInputKey:@"Food_In"];
        best_food_x_loc = convertToQCX([[qcView valueForOutputKey:@"Food_1_X"] floatValue]);
        best_food_y_loc = convertToQCY([[qcView valueForOutputKey:@"Food_1_Y"] floatValue]);
        NSLog(@"X:%f, Y:%f",best_food_x_loc, best_food_y_loc);
    } else {
        [qcView setValue:yeah forInputKey:@"Food_In"];
    }
}

Upvotes: 0

Views: 707

Answers (1)

Lucas Derraugh
Lucas Derraugh

Reputation: 7049

You have to set your NSView to be first responder

- (BOOL)acceptsFirstResponder { return YES; }

Upvotes: 2

Related Questions