Last active
March 16, 2023 12:36
-
-
Save IsaacXen/2caab7c62867fc1db0e695d0d121c2b0 to your computer and use it in GitHub Desktop.
NSTextField subclass with focus and blur callback.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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