How to determine if NSSearchField / NSTextField has input focus?

How to determine if input focus has NSSearchField / NSTextField?

+8
cocoa macos
source share
2 answers

The previous answer is incorrect, because NSTextField / NSSearchField themselves do not become the first responder and process the edited text. Instead, they use the window's field editor, which is an NSTextView that is shared between all the fields of the window (since only one of them can have focus at a time).

You need to see if the first responder is an NSText , and if so, if the search field / text field is its delegate.

 NSResponder *firstResponder = [[NSApp keyWindow] firstResponder]; if ([firstResponder isKindOfClass:[NSText class]] && [(id)firstResponder delegate] == mySearchField) { NSLog(@"Yup."); } 
+24
source share

Although Greg Titus' answer probably works, I think the best way is:

 BOOL isFirstResponder = mySearchField.currentEditor == mySearchField.window.firstResponder; 
+2
source share