Skip to content

Instantly share code, notes, and snippets.

@NghiaTranUIT
Created December 7, 2020 12:56
Show Gist options
  • Save NghiaTranUIT/b502098644c66f9b8631ec1b6e93c3ac to your computer and use it in GitHub Desktop.
Save NghiaTranUIT/b502098644c66f9b8631ec1b6e93c3ac to your computer and use it in GitHub Desktop.
NSTextFiels check isFocus
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