How to observe focus event of NSTextField in macOS

Issue #589

becomeFirstResponder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class FocusAwareTextField: NSTextField {
var onFocusChange: (Bool) -> Void = { _ in }

override func becomeFirstResponder() -> Bool {
let textView = window?.fieldEditor(true, for: nil) as? NSTextView
textView?.insertionPointColor = R.nsColor.action
onFocusChange(true)
return super.becomeFirstResponder()
}
}

textField.delegate // NSTextFieldDelegate
func controlTextDidEndEditing(_ obj: Notification) {
onFocusChange(false)
}

NSTextField and NSText

https://stackoverflow.com/questions/25692122/how-to-detect-when-nstextfield-has-the-focus-or-is-its-content-selected-cocoa

When you clicked on search field, search field become first responder once, but NSText will be prepared sometime somewhere later, and the focus will be moved to the NSText.

I found out that when NSText is prepared, it is set to self.currentEditor() . The problem is that when becomeFirstResponder()’s call, self.currentEditor() hasn’t set yet. So becomeFirstResponder() is not the method to detect it’s focus.

On the other hand, when focus is moved to NSText, text field’s resignFirstResponder() is called, and you know what? self.currentEditor() has set. So, this is the moment to tell it’s delegate that that text field got focused

Use NSTextView

Any time you want to customize NSTextField, use NSTextView instead

1
2
3
4
5
6
7
8
// NSTextViewDelegate
func textDidBeginEditing(_ notification: Notification) {
parent.isFocus = true
}

func textDidEndEditing(_ notification: Notification) {
parent.isFocus = false
}

Comments