Last active
June 23, 2020 06:09
-
-
Save Dimillian/63d02ea9cee363f360ecf76a26955097 to your computer and use it in GitHub Desktop.
An example on how to do a SearchField with SwiftUI
This file contains hidden or 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
struct SearchField : View { | |
@Binding var searchText: String | |
let placeholder: Text | |
let onUpdateSearchText: (String) -> Void | |
func onKeyStroke() { | |
onUpdateSearchText(searchText) | |
} | |
var body: some View { | |
HStack(alignment: .center, spacing: -10) { | |
Image(systemName: "magnifyingglass") | |
TextField($searchText, | |
placeholder: Text("Search any movies")) | |
.onReceive(NotificationCenter.default.publisher(for: UITextField.textDidChangeNotification) | |
.debounce(for: 0.5, | |
scheduler: DispatchQueue.main), | |
perform: onKeyStroke) | |
.textFieldStyle(.roundedBorder) | |
.listRowInsets(EdgeInsets()) | |
.padding() | |
if !searchText.isEmpty { | |
Button(action: { | |
self.searchText = "" | |
}, label: { | |
Text("cancel").color(.blue) | |
}).animation(.basic()) | |
} | |
} | |
} | |
} | |
#if DEBUG | |
struct SearchField_Previews : PreviewProvider { | |
static var previews: some View { | |
SearchField(searchText: .constant("Searched text"), | |
placeholder: Text("Search anything"), | |
onUpdateSearchText: {text in | |
}) | |
} | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment