Skip to content

Commit d184234

Browse files
Fix NSSearchField clear button behavior
1 parent 92098ab commit d184234

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

WWDC/Util/SearchField.swift

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,23 @@ struct SearchField: NSViewRepresentable {
4545
self.parent = parent
4646
}
4747

48+
/// This is delayed via NSSearchField behavior
4849
@objc
49-
func searchFieldAction(_ sender: Any) {
50-
parent.onSearch()
50+
func searchFieldAction(_ sender: NSSearchField) {
51+
DispatchQueue.main.async { [parent] in
52+
// controlTextDidChange guarantees immediate text entry updates are relayed to SwiftUI state,
53+
// but when the clear button is clicked, the action is sent before that state update happens.
54+
//
55+
// Additionally, this is just prudent to ensure state is in sync before sending the search action.
56+
if parent.text != sender.stringValue {
57+
parent.text = sender.stringValue
58+
}
59+
60+
parent.onSearch()
61+
}
5162
}
5263

64+
/// This is immediately called as the user types
5365
func controlTextDidChange(_ obj: Notification) {
5466
let value = (obj.object as? NSSearchField)?.stringValue ?? ""
5567
if parent.text != value {

0 commit comments

Comments
 (0)