0

I'm trying to subclass NSTokenField to intercept some of the keyboard events. I wrote subclasses for NSTokenField, NSTokenFieldCell and NSTextView. In the NSTokenField subclass I swap the regular cell with my custom cell and in the custom cell I override -(NSTextView*)fieldEditorForView:(NSView *)aControlView to provide my textview as a custom field editor. All the initialisation methods are called as expected but for some reason my custom token field is not drawn.

Here is the code for the NSTokenField subclass:

@synthesize fieldEditor = _fieldEditor;

-(JSTextView *)fieldEditor
{
    if (!_fieldEditor) {
        _fieldEditor = [[JSTextView alloc] init];
        [_fieldEditor setFieldEditor:YES];
    }
    return _fieldEditor;
}

- (void)awakeFromNib {
    JSTokenFieldCell *newCell = [[JSTokenFieldCell alloc] init];
    [self setCell:newCell];
}

+ (Class) cellClass
{
    return [JSTokenFieldCell class];
}

- (id)initWithFrame:(NSRect)frameRect
{
    self = [super initWithFrame:frameRect];
    if (self) {
        JSTokenFieldCell *newCell = [[JSTokenFieldCell alloc] init];
        [self setCell:newCell];
    }
    return self;
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        JSTokenFieldCell *newCell = [[JSTokenFieldCell alloc] initWithCoder:aDecoder];
        [self setCell:newCell];
    }
    return self;
}

And here is the code for the subclass of NSTokenFieldCell:

-(NSTextView*)fieldEditorForView:(NSView *)aControlView
{
if ([aControlView isKindOfClass:[JSTokenField class]]) {
    JSTokenField *tokenField = (JSTokenField *)aControlView;
    return tokenField.fieldEditor;
    }
return nil;
}

- (id)initWithCoder:(NSCoder *)decoder
{
    return [super initWithCoder:decoder];
}

- (id)initTextCell:(NSString *)aString
{
    return [super initTextCell:aString];
}

- (id)initImageCell:(NSImage *)anImage
{
    return [super initImageCell:anImage];
}

Addition

After further digging I found this post which says that the only way to have an NSTokenField with a custom text view is by overriding private methods. Is it true? If so, is there any other way I can intercept keyboard events without subclassing NSTextView?

Jacopo
  • 1,031
  • 2
  • 12
  • 25

0 Answers0