How can i add menu items to the context menu of a NSTextField
I tried to overwrite the simple NSView method:
- (NSMenu *)menuForEvent:(NSEvent *)event {
NSMenu* result = [super menuForEvent: event];
NSMenuItem* mi = [[NSMenuItem alloc] initWithTitle: @"Foobar" action: @selector(foobar) keyEquivalent: @""];
[result addItem: mi];
return result;
}
but it d开发者_运维问答oes not work. It is never called.
Try to use the NSTextViewDelegate Protocol
- (NSMenu *)textView:(NSTextView *)view menu:(NSMenu *)menu forEvent:(NSEvent *)event atIndex:(NSUInteger)charIndex
The window's field editor will then ask your NSTextField for the menu
If the text field has focus, I believe the menu you're getting is actually that of the Field Editor. Maybe ask it for its menu.
Thanks for others pointing the way. I haven't been able to get the window's default field editor to use any delegate methods. Finally I put the following in my window delegate's -windowDidLoad method
NSTextView* defaultFieldEditor = [self.window fieldEditor:YES forObject:nil];
// defaultEditor.delegate = self; didn't help
NSMenu *mu = defaultEditor.menu;
[mu insertItem:[NSMenuItem separatorItem] atIndex:0];
[mu insertItemWithTitle:@"Insert Line"
action:@selector(acnInsertLine:)
keyEquivalent:@"" atIndex:0];
[mu insertItemWithTitle:@"Delete Line"
action:@selector(acnDeleteLine:)
keyEquivalent:@"" atIndex:0];
This is supposed to put the items at the beginning (so reverse order). You could use addItem:
instead. Both suffer from the problem that the contents of the menu vary and your items are likely to up somewhere in the middle.
Note that the field editor is a NSTextView even if the control it covers is a NSTextField. This has caused me some perplexity.
精彩评论