Skip to content

Instantly share code, notes, and snippets.

@TonyTang2001
Last active July 24, 2020 23:55
Show Gist options
  • Save TonyTang2001/edb29c40e424baf45e27038dafd7b716 to your computer and use it in GitHub Desktop.
Save TonyTang2001/edb29c40e424baf45e27038dafd7b716 to your computer and use it in GitHub Desktop.
SwiftUI SearchBar Wrapped from UIKit as there is no built-in version available.
struct SearchBarView: UIViewRepresentable {
@Binding var text: String
var placeholder: 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 searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
// Clear search bar text after cance button is clicked
text = ""
// Exit editing mode, dismiss keyboard, and hide Cancel button
searchBar.endEditing(true)
searchBar.setShowsCancelButton(false, animated: true)
}
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(true, animated: true)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
// Exit editing mode, dismiss keyboard
searchBar.endEditing(true)
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
// Function called when searchbar has exited editing mode
// When textfield is empty and edit mode is exited, there's no need to show "Cancel" button
if text.isEmpty {
searchBar.setShowsCancelButton(false, animated: 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.placeholder = placeholder
searchBar.searchBarStyle = .minimal
// Disable auto-capitalization of first character
searchBar.autocapitalizationType = .none
// Hide "Cancel" button by default
searchBar.setShowsCancelButton(false, animated: true)
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