0

How can I get a notification when the textfield has ended editing (enter key pressed, clicked outside the text field, clicked inside the same column, but outside the text field, etc)

I checked

- (void)textDidEndEditing:(NSNotification *)aNotification
{
   //some code here
}

but this notification is only called when the text has actually changed. I need to be notified even if no text changes have been made.

Edit: Some sort of notification that the first responder has changed would work as well.

Any ideas?

Bhavesh Nayi
  • 3,626
  • 1
  • 27
  • 42

1 Answers1

0

Observe the firstResponder state of the window …

…
[theWindow addObserver:self forKeyPath:@"firstResponder" options:NSKeyValueObservingOptionOld context:NULL];
…

… and read the field editor's delegate:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
  if ([keyPath isEqualToString:@"firstResponder"])
  {
    NSResponder *oldResponder =change[NSKeyValueChangeOldKey];
    if ([oldResponder isKindOfClass:[NSTextView class]])
    {
      NSTextView *editor = (NSTextView*)oldResponder;
      NSTextField *textField = (NSTextField*)editor.delegate;
      NSLog(@"This text field lost the focus: %@", textField.identifier);
    }
  }
}
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
  • It appears that this is called when the textfield is focussed, not when it looses focus, although I set `options:NSKeyValueObservingOptionOld`. Can you imagine why? – Julian F. Weinert Jan 10 '15 at 17:15
  • It is not called or do jump over an if statement? Please, set a breakpoint to the first `if`. – Amin Negm-Awad Jan 12 '15 at 09:05
  • As I commented; there is no if when I don't mention it ;-) Strange enough, isn't it? – Julian F. Weinert Jan 12 '15 at 09:08
  • It is strange. "In OS X v10.6 and later, firstResponder is key-value observing compliant." The option is without any meaning, because the are options for the passed data, not for the event, that sends the message. Have to make a test project, but do not have enough time today. – Amin Negm-Awad Jan 12 '15 at 09:18
  • This really drives me nuts and I don't get why... I mean I'm getting notifs for the last responder, so it does work, but not completely... – Julian F. Weinert Jan 12 '15 at 09:21
  • 1
    When an NSTextField receives focus, it immediately creates a field editor (an NSTextView) and gives that keyboard focus. So NSTextFields never have keyboard focus while they're being edited. Could that be the weird behaviour you are seeing? – uliwitness Feb 16 '15 at 11:13