NSTextField:当用户在文本字段之外单击时结束编辑 [英] NSTextField: end editing when user clicks outside of the text field
问题描述
我有一个 NSTextField
,我可以根据用户操作对其进行设置。当用户单击窗口内文本字段之外的任意位置时,我想结束编辑。
I have an NSTextField
that I'm setting editable depending on a user action. I'd like to end editing when the user clicks anywhere outside of the text field inside the window.
看似简单,但我无法做到这一点。我实现了 controlTextDidEndEditing
和 textDidEndEditing
,但是没有运气,尤其是当我单击不接受
Seems simple, but I could not get this to work. I implemented controlTextDidEndEditing
and textDidEndEditing
, but no luck, especially when I click on a user interface element that does not accept the first responder status.
推荐答案
每个NSEvent都通过NSWindow的 sendEvent传递:
Every NSEvent is pass through NSWindow's sendEvent:
method.
您可以创建自定义NSWindow并覆盖 sendEvent:
方法。如果发生鼠标按下事件,请通过NSNotificationCenter进行广播:
You can create a custom NSWindow and override the sendEvent:
method. If there is a mouse down event, broadcast it by the NSNotificationCenter:
- (void)sendEvent:(NSEvent *)event {
[super sendEvent:event];
if (event.type == NSLeftMouseDown) {
[[NSNotificationCenter defaultCenter] postNotificationName:kCustomWindowMouseDown object:self userInfo:@{@"event": event}];
}
}
在ViewController中,引用NSTextField,观察者此通知:
In the ViewController which reference the NSTextField, observer this notification:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(customWindowMouseDown:)
name:kCustomWindowMouseDown
object:self.view.window];
如果鼠标向下事件的位置不在文本范围内,则结束编辑字段:
End the editing if the mouse down event's location is outside of the text field:
- (void)customWindowMouseDown:(id)sender {
NSNotification *notification = (NSNotification *) sender;
NSEvent *event = notification.userInfo[@"event"];
NSPoint locationInWindow = event.locationInWindow;
if ([self.view.window.firstResponder isKindOfClass:NSTextView.class]) {
NSTextView *firstResponder = (NSTextView *) self.view.window.firstResponder;
//we only care about the text field referenced by current ViewController
if (firstResponder.delegate == (id <NSTextViewDelegate>) self.textField) {
NSRect rect = [self.textField convertRect:self.textField.bounds toView:nil];
//end editing if click out side
if (!NSPointInRect(locationInWindow, rect)) {
[self.view.window makeFirstResponder:nil];
}
}
}
}
这篇关于NSTextField:当用户在文本字段之外单击时结束编辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!