Skip to content

Instantly share code, notes, and snippets.

@Dimillian
Last active June 23, 2020 06:09
Show Gist options
  • Save Dimillian/63d02ea9cee363f360ecf76a26955097 to your computer and use it in GitHub Desktop.
Save Dimillian/63d02ea9cee363f360ecf76a26955097 to your computer and use it in GitHub Desktop.
An example on how to do a SearchField with SwiftUI
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