Intercept Keydown Actions in an NSTextFieldCell

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!


    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;
    }
    
    链接地址: http://www.djcxy.com/p/85212.html

    上一篇: NSOutlineView将不会重新加载keydown上的数据,而是重点更新

    下一篇: 在NSTextFieldCell中拦截Keydown操作