I think I nailed it. I tried to subclass NSTextFiled to override becomeFirstResponder() and resignFirstResponder() , but as soon as I click on it, becomeFirstResponder() is called and resignFirstResponder() is called right after that. A? But the search box is still under editing, and the focus is still on it.
I realized that when you click on the search field, the search field will become the first responder once, but NSText will be prepared somewhere later, and the focus will be transferred to NSText .
I found out that when an NSText prepared, it is set to self.currentEditor() . The problem is that when the call becomeFirstResponder() , self.currentEditor() is not set yet. Thus, becomeFirstResponder() not a focus detection method.
On the other hand, when the focus is moved to an NSText , the resignFirstResponder() text field is resignFirstResponder() , and you know what? self.currentEditor() . So, the time has come to inform the delegate that this text box has been focused.
Then, how to determine when the search field has lost focus. Again, this is about an NSText . Then you need to listen to the NSText delegate NSText , such as textDidEndEditing() , and make sure that you allow the superclass to process this method and see if self.currentEditor() . If so, NSText lost focus and informed the delegate of the text field about it.
I provide code, in fact an NSSearchField subclass, to do the same. And the same principle should work for NSTextField .
protocol ZSearchFieldDelegate: NSTextFieldDelegate { func searchFieldDidBecomeFirstResponder(textField: ZSearchField) func searchFieldDidResignFirstResponder(textField: ZSearchField) } class ZSearchField: NSSearchField, NSTextDelegate { var expectingCurrentEditor: Bool = false
You will need to change the NSSerachField to ZSearchField , and your client class should match ZSearchFieldDelegate not NSTextFieldDelegate . Here is an example. When the user clicked on the search field, it expanded its width, and when you click on another place, the search field lost focus and reduced its width by changing the NSLayoutConstraint value set by the interface constructor.
class MyViewController: NSViewController, ZSearchFieldDelegate {
It may depend on the behavior of the OS, I tried El Capitan 10.11.4 and it worked.
Code can also be copied from Gist. https://gist.github.com/codelynx/aa7a41f5fd8069a3cfa2