Skip to content

Instantly share code, notes, and snippets.

@roddymunro
Last active September 8, 2020 00:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roddymunro/877c0aeeef5016d454c8add194b60a5a to your computer and use it in GitHub Desktop.
Save roddymunro/877c0aeeef5016d454c8add194b60a5a to your computer and use it in GitHub Desktop.
Code for my tutorial about making your Picker's searchable.
import SwiftUI
struct SearchBar: UIViewRepresentable {
@Binding var text: String
var placeholder: String
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
searchBar.placeholder = placeholder
searchBar.autocapitalizationType = .none
searchBar.searchBarStyle = .minimal
return searchBar
}
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) {
uiView.text = text
}
func makeCoordinator() -> SearchBar.Coordinator {
return Coordinator(text: $text)
}
class Coordinator: NSObject, UISearchBarDelegate {
@Binding var text: String
init(text: Binding<String>) {
_text = text
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
text = searchText
}
}
}
struct FormView: View {
let countries = ["Brazil", "Canada", "Egypt", "France", "Germany", "United Kingdom"]
@State private var pickerSelection: String = ""
@State private var searchTerm: String = ""
var filteredCountries: [String] {
countries.filter {
searchTerm.isEmpty ? true : $0.lowercased().contains(searchTerm.lowercased())
}
}
var body: some View {
NavigationView {
Form {
Picker(selection: $pickerSelection, label: Text("")) {
SearchBar(text: $searchTerm, placeholder: "Search Countries")
ForEach(filteredCountries, id: \.self) { country in
Text(country).tag(country)
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment