解决方法
我厌倦了所有的非答案,以其他方式做到这一点,所以我放下了我的头,找到了一种方法来使这项工作.这不是直接使用keydown事件,而是使用块中的keydown.而这种行为正是我想要的.
子类化文本字段
.H
@interface LQRestrictedInputTextField : NSTextField
.M
在成为第一响应者设置本地事件
static id eventMonitor = nil; - (BOOL)becomeFirstResponder { BOOL oktochange = [super becomeFirstResponder]; if (oktochange) { [self setKeyboardFocusRingNeedsDisplayInRect: [self bounds]]; if (!eventMonitor) { eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask handler:^(NSEvent *event) { NSString *characters = [event characters]; unichar character = [characters characterAtIndex:0]; NSString *characterString=[NSString stringWithFormat:@"%c",character]; NSArray *validNonAlphaNumericArray = @[@" ",@"(",@")",@"[",@"]",@":",@";",@"\'",@"\"",@".",@"<",@">",@",",@"{",@"}",@"|",@"=",@"+",@"-",@"_",@"?",@"#",@(NSDownArrowFunctionKey),@(NSUpArrowFunctionKey),@(NSLeftArrowFunctionKey),@(NSRightArrowFunctionKey)]; if([[NSCharacterSet alphanumericCharacterSet] characterIsMember:character] || character == NSCarriageReturnCharacter || character == NSTabCharacter || character == NSDeleteCharacter || [validNonAlphaNumericArray containsObject:characterString ] ) { //[NSCharacterSet alphanumericCharacterSet] } else { NSBeep(); event=nil; } return event; } ]; } } NSLog(@"become first responder"); return oktochange; }
文本字段编辑结束后删除事件
此外,如果您使用ARC我注意到您可能需要将textview字符串分配给stringValue.我nslog了stringValue并保留了值.如果没有nslog,我必须将通知对象字符串分配给stringValue以防止它被释放.
-(void) textDidEndEditing:(NSNotification *)notification { [NSEvent removeMonitor:eventMonitor]; eventMonitor = nil; NSTextView *textView=[notification object]; self.stringValue=textView.string; }