Created
December 7, 2020 12:56
-
-
Save NghiaTranUIT/b502098644c66f9b8631ec1b6e93c3ac to your computer and use it in GitHub Desktop.
NSTextFiels check isFocus
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 AppKit | |
// Credit: Vadim Shpakovski from AppKitAbusers | |
class ViewController: NSViewController { | |
let textField1: CustomTextField = .init(string: "Field 1") | |
let textField2: CustomTextField = .init(string: "Field 2") | |
var observation1: NSKeyValueObservation? | |
var observation2: NSKeyValueObservation? | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
let stackView = NSStackView(views: [textField1, textField2]) | |
stackView.translatesAutoresizingMaskIntoConstraints = false | |
stackView.orientation = .vertical | |
view.addSubview(stackView) | |
NSLayoutConstraint.activate([ | |
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor), | |
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor), | |
stackView.widthAnchor.constraint(equalToConstant: 200), | |
]) | |
observation1 = textField1.observe(\.isFocused) { textField, _ in | |
print(textField.stringValue, textField.isFocused ? "is focused" : "is not focused") | |
} | |
observation2 = textField2.observe(\.isFocused) { textField, _ in | |
print(textField.stringValue, textField.isFocused ? "is focused" : "is not focused") | |
} | |
} | |
} | |
class CustomTextField: NSTextField { | |
@objc dynamic var isFocused: Bool { currentEditor() != nil } | |
override func becomeFirstResponder() -> Bool { | |
let result = super.becomeFirstResponder() | |
willChangeValue(for: \.isFocused) | |
didChangeValue(for: \.isFocused) | |
return result | |
} | |
override func textDidEndEditing(_ notification: Notification) { | |
super.textDidEndEditing(notification) | |
willChangeValue(for: \.isFocused) | |
didChangeValue(for: \.isFocused) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment