Question

I have a cell-based NSOutlineView which displays NSTextFieldCell objects.

I'd like to respond to keydown or keyup events so as to make the text contained in the NSTextFieldCell bold when the text contains certain preset keywords. What is the most elegant way to achieve this - should I:

  • Subclass NSOutlineView and override the keydown method
  • Subclass NSTextFieldCell
  • Utilize a delegate of some kind
  • Utilize some other approach

Thanks very much in advance to all for any info!

No correct solution

OTHER TIPS

Found it.

In awakeFromNib:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionToTakeOnKeyPress:)  name:NSControlTextDidChangeNotification object:theNSOutlineViewThatContainsTheNSTextFieldCell]; 

Then add a method like this:

- (void) actionToTakeOnKeyPress: (id) sender
{
    //will be called whenever contents of NSTextFieldCell change
}

To intercept key presses in a way that they can still be filtered out, various NSResponder messages may be overwritten, such as keyDown: or interpretKeyEvents:.

To be able to do that, a subclass of a NSTextView needs to be used as the field editor. For that, one subclasses NSTextFieldCell and overrides fieldEditorForView:, returning the subclass (see Custom field editor for NSTextFieldCell in an NSTableView).

Here's the relevant code excerpts:

In a subclassed NSTextFieldCell (which then has to be assigned in Interface Builder for the editable column, or returned by the NSTableViewDelegate's dataCellForTableColumn message):

- (NSTextView *)fieldEditorForView:(NSView *)aControlView
{
    if (!self.myFieldEditor) {
        self.myFieldEditor = [[MyTextView alloc] init];
        self.myFieldEditor.fieldEditor = YES;
    }
    return self.myFieldEditor;    
}

It also requires the declaration of a property in the @interface section:

@property (strong) MyTextView *myFieldEditor;

And then in MyTextView, which is a subclass of NSTextView:

-(void)keyDown:(NSEvent *)theEvent
{
    NSLog(@"MyTextView keyDown: %@", theEvent.characters);
    static bool b = true;
    if (b) { // this silly example only lets every other keypress through.
        [super keyDown:theEvent];
    }
    b = !b;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top