Question

I am a newbie in OSx development.

I have a Cocoa application which uses a Webview. Everything is working fine, except for the textfield in the webview. I know how to enable keystrokes in NSTextField, but not the ones in the Webview. I've been searching the web all day, but with no luck. I badly need some help on how to enable the keystrokes to implement keyboard shortcut keys.

Example:

copy -> command + c

paste -> command + v

cut -> command + x

Any help would be very much appreciated.

Was it helpful?

Solution

I got the answer now. I've realized that I forgot to implement

- (BOOL)performKeyEquivalent:(NSEvent *)theEvent

to the class which handles the Webview.

OTHER TIPS

@Kimpoy, thanks for the reference to performKeyEquivalent! For completeness, I implemented it this way...

Subclass your webview from WebView and implement the method:

- (BOOL)performKeyEquivalent:(NSEvent *)theEvent {

    NSString * chars = [theEvent characters];
    BOOL status = NO;

    if ([theEvent modifierFlags] & NSCommandKeyMask){

        if ([chars isEqualTo:@"a"]){
            [self selectAll:nil];
            status = YES;
        }

        if ([chars isEqualTo:@"c"]){
            [self copy:nil];
            status = YES;
        }

        if ([chars isEqualTo:@"v"]){
            [self paste:nil];
            status = YES;
        }

        if ([chars isEqualTo:@"x"]){
            [self cut:nil];
            status = YES;
        }
    }

    if (status)
        return YES;

    return [super performKeyEquivalent:theEvent];
}

Credit to @aventurella over here: https://github.com/Beats-Music/mac-miniplayer/issues/3. Just modified slightly to return the super response as default because it should propagate down to its subviews.

As a note, I'd recommend implementing a log or similar in your custom webview to make sure you really are working with your class:

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];

    // Drawing code here.

    NSLog(@"Custom webview running...");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top