SwiftUI searchable modifier in iOS 15
In iOS 15, SwiftUI added a new searchable modifier. It directly gets added into a NavigationView.
The searchable text field automatically adjusts the layout and fits properly in it.
Before directly jumping into a View. Let’s have data to be populated into a View.
Let’s build a list view to populate cities with respective weather.
We just have to apply the searchable modifier to the view to mark the respective view as searchable, which configures the display of a search field.
Use this modifier to create a user interface appropriate for searching.
Wrapping a navigation view results in a column of the navigation view displaying a search field.
/// — Parameters:
/// — text: The text to display and edit in the search field./// — placement: The preferred placement of the search field within the/// containing view hierarchy.@available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)public func searchable(text: Binding<String>, placement: SearchFieldPlacement = .automatic) -> some View
Let’s add a Binding property.
@State var searchFor: String = “”
Add modifier to the respective view.
.searchable(text: $searchFor, placement: .automatic)
Tadaa… here is the search field associated with our List.
NOTE: Nothing will happen because, We are yet to add the handling for the search query.
We just need to add a filter based on the searchFor query and pass the result array to the list instead of viewModel.modelData.
It’s started working with our search query!!!!
It doesn’t just stop there!!! They do have exclusive features for all of us. Provide suggestions to the user. i.e., Autocomplete. By just adding a searchCompletion(_:).
You can customize the search view like add image, color, etc. and even adding extra completion information to save them typing so much.
Other SwiftUI 15 blogs you might want to take a look,
- SwiftUI iOS 15 refreshable modifier
- SwiftUI iOS 15 swipeActions modifier