As SwiftUI completes a year, there’s a lot to look forward to from WWDC 2020. Having an out-of-the-box search bar functionality should be on everyone’s wishlist.
Until then, we can leverage the SwiftUI-UIKit interoperability to build a custom search bar.
In the following sections, we’ll be building a SwiftUI application for searching contacts.
UIViewRepresentable
protocol to create a UISearchBar
wrapper for SwiftUI.The Contacts framework lets you read information without making any changes. In order to access that in your application, we first need to set the privacy usage descriptions in the info.plist
file. Just add the NSContactsUsageDescription
key with a string value explaining the need for the permission.
SwiftUI doesn’t come with built-in functionality for search bars. So, we need to conform our struct to the UIViewRepresentable
protocol and initialize the UIKit’s UISearchBar
instance in it as shown below:
struct SearchBarView: UIViewRepresentable {
@Binding var text: String
var placeholder: String
func makeCoordinator() -> Coordinator {
return Coordinator(text: $text)
}
func makeUIView(context: Context) -> UISearchBar {
let searchBar = UISearchBar(frame: .zero)
searchBar.delegate = context.coordinator
searchBar.placeholder = placeholder
searchBar.searchBarStyle = .minimal
searchBar.autocapitalizationType = .none
searchBar.showsCancelButton = true
return searchBar
}
func updateUIView(_ uiView: UISearchBar,
context: Context) {
uiView.text = text
}
}
The makeCoordinator()
function lets us create a Coordinator
class, which is responsible for communicating changes from our UIKit view to the SwiftUI interface. Let’s define the Coordinator
class, which also declares the UISearchBarDelegate
protocol:
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) {
searchBar.resignFirstResponder()
}
}
#programming #swift #mobile #ios #swiftui