How to make focusable NSTextField in macOS
Issue #589
Use onTapGesture
1 | import SwiftUI |
becomeFirstResponder
1 | class FocusAwareTextField: NSTextField { |
NSTextField and NSText
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 | // NSTextViewDelegate |
Updated at 2021-02-23 22:32:07