This sample demonstrates how to create a table view controller and search controller to manage the display of searchable content. It creates another custom table view controller to display the search results. This table view controller also acts as the presenter or provides context for the search results so they’re presented within their own context.
This sample includes the optional—but recommended—UIStateRestoring protocol. You adopt this protocol from the view controller class to save the search bar’s active state, first responder status, and search bar text and restore them when the app is relaunched.
Create a Search Controller
Use MainTableViewController, a subclass of UITableViewController, to create a search controller. The search controller searches and filters a set of Product objects and displays them in a table called ResultsTableController. This table controller is displayed as the user enters a search string and is dismissed when the search is complete.
There are two ways to create the search controller in MainTableViewController, depending on the iOS version. In iOS 10 and earlier, you place it inside the table view’s header. In iOS 11 and later, you place it in the view controller’s navigation bar.
Update the Search Results
This sample uses the UISearchResultsUpdating protocol, along with NSComparisonPredicate, to filter out search results from the group of available products. NSComparisonPredicate is a foundation class that specifies how data should be fetched or filtered using search criteria. The search criteria are based on what the user types in the search bar, which can be a combination of product title, year introduced, and price.
To prepare for a search, the search bar content is trimmed of all leading and trailing space characters. Then the search string is passed to the findMatches function, which returns the NSComparisonPredicate used in the search. The product list results are applied to the search results table as a filtered list.
Initializes a predicate to a given type formed by combining given left and right expressions using a given modifier and options.
This documentation contains preliminary information about an API or technology in development. This information is subject to change, and software implemented according to this documentation should be tested with final operating system software.