Skip to content

Instantly share code, notes, and snippets.

@IsaacXen
Last active March 16, 2023 12:36
Show Gist options
  • Save IsaacXen/2caab7c62867fc1db0e695d0d121c2b0 to your computer and use it in GitHub Desktop.
Save IsaacXen/2caab7c62867fc1db0e695d0d121c2b0 to your computer and use it in GitHub Desktop.
NSTextField subclass with focus and blur callback.
import Cocoa
protocol TextFieldDelegate: class {
func textFieldDidBecomeFirstResponder(_ textField: TextField)
func textFieldDidResignFirstResponder(_ textField: TextField)
}
class TextField: NSTextField {
weak var firstResponderDelegate: TextFieldDelegate?
private var isFocused = false {
didSet {
if isFocused {
firstResponderDelegate?.textFieldDidBecomeFirstResponder(self)
} else {
firstResponderDelegate?.textFieldDidResignFirstResponder(self)
}
}
}
override func resignFirstResponder() -> Bool {
let willResign = super.resignFirstResponder()
if willResign, let _ = currentEditor() {
isFocused = true
}
return status
}
override func textDidEndEditing(_ notification: Notification) {
super.textDidEndEditing(notification)
if currentEditor() == nil {
onceFocus = false
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment