在NSTextFieldCell中拦截Keydown操作
  我有一个基于单元格的NSOutlineView显示NSTextFieldCell对象。 
我想回应keydown或keyup事件,以便在文本包含某些预设关键字时使NSTextFieldCell中的文本变为粗体。 什么是最优雅的方式来实现这一点 - 我应该:
非常感谢所有的信息!
找到了。
在awakeFromNib中:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionToTakeOnKeyPress:)  name:NSControlTextDidChangeNotification object:theNSOutlineViewThatContainsTheNSTextFieldCell]; 
然后添加一个像这样的方法:
- (void) actionToTakeOnKeyPress: (id) sender
{
    //will be called whenever contents of NSTextFieldCell change
}
  要以仍然可以过滤的方式拦截按键,可能会覆盖各种NSResponder消息,例如keyDown:或interpretKeyEvents: NSResponder 
  为了做到这一点,需要将NSTextView的子类用作字段编辑器。  为此,一个子类NSTextFieldCell并重写fieldEditorForView:返回子类(请参阅NSTableView中的NSTextFieldCell的自定义字段编辑器)。 
以下是相关的代码摘录:
  在子类NSTextFieldCell (然后必须在Interface Builder中为可编辑列分配,或者由NSTableViewDelegate的dataCellForTableColumn消息返回): 
- (NSTextView *)fieldEditorForView:(NSView *)aControlView
{
    if (!self.myFieldEditor) {
        self.myFieldEditor = [[MyTextView alloc] init];
        self.myFieldEditor.fieldEditor = YES;
    }
    return self.myFieldEditor;    
}
  它还需要在@interface部分声明一个属性: 
@property (strong) MyTextView *myFieldEditor;
  然后在MyTextView ,它是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;
}
上一篇: Intercept Keydown Actions in an NSTextFieldCell
下一篇: How do I cut and paste text from within a NSTextFieldCell in an NSOutlineView
