Last active
March 11, 2021 19:06
-
-
Save iamidzic/82617e1a669888ac36ac4a214fc80db5 to your computer and use it in GitHub Desktop.
SearchBar for SwiftUI
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
struct SearchBar: UIViewRepresentable { | |
@Binding var text: String | |
class Coordinator: NSObject, UISearchBarDelegate { | |
@Binding var text: String | |
init(text: Binding<String>) { | |
_text = text | |
} | |
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { | |
text = searchText | |
} | |
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { | |
searchBar.resignFirstResponder() | |
} | |
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { | |
searchBar.text = "" | |
searchBar.endEditing(true) | |
} | |
} | |
func makeCoordinator() -> SearchBar.Coordinator { | |
return Coordinator(text: $text) | |
} | |
func makeUIView(context: UIViewRepresentableContext<SearchBar>) -> UISearchBar { | |
let searchBar = UISearchBar(frame: .zero) | |
searchBar.delegate = context.coordinator | |
searchBar.showsCancelButton = true | |
searchBar.autocapitalizationType = .none | |
return searchBar | |
} | |
func updateUIView(_ uiView: UISearchBar, context: UIViewRepresentableContext<SearchBar>) { | |
uiView.text = text | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment