Last active
September 8, 2020 00:41
-
-
Save roddymunro/877c0aeeef5016d454c8add194b60a5a to your computer and use it in GitHub Desktop.
Code for my tutorial about making your Picker's searchable.
This file contains 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
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