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.


Plan of Action

  • Use the Contacts framework to fetch your phone contacts.
  • Populate them in a SwiftUI List.
  • Use the UIViewRepresentable protocol to create a UISearchBar wrapper for SwiftUI.
  • Filter the SwiftUI contacts list based on searched text.

Get Started — Add Privacy Descriptions

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.


Wrap UISearchBar With UIViewRepresentable and Coordinators

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

Build a SwiftUI Contacts Search Application
15.60 GEEK