To complement a view controller’s large title, it’s also possible to add a search bar, which allows users to quickly find content without navigating to a new screen. Widely used in iOS applications, Apple’s Human Interface Guidelines provide a good overview of search bars.
Entering a term in the search bar initiates a search through the book list for relevant results. The various classes and methods that enable a search bar are described below.
Searchable View Controller
In this example, the searchable view controller is represented in code as the LargeTitlesViewController class, which is defined by partial classes in two files: LargeTitlesViewController.cs and LargeTitlesViewController+Search.cs.
UISearchController
iOS uses the UISearchController class to tie together the various bits that must cooperate to enable a search bar. UISearchController creates the search bar UI and automatically calls the method to run a search for a user’s query.
In LargeTitlesViewController+Search.cs, the ViewDidLoad method instantiates the UISearchController:
Search results can be visualized in many ways. Some data should be shown as a list, while other data might best be represented on a map. You can pass a view controller for displaying search results to the searchResultsController parameter of the UISearchController constructor or set this value to null to indicate that search results should be displayed using the searchable view controller itself.Search Results Updater
When the UISearchController needs to kick off a search for a user’s query, it calls the UpdateSearchResultsForSearchController method on its SearchResultsUpdater. This property implements the IUISearchResultsUpdating interface, which has only one method:
{
// …
search.SearchResultsUpdater = this;
// …
}public void UpdateSearchResultsForSearchController(UISearchController searchController)
{
var find = searchController.SearchBar.Text;
if (!String.IsNullOrEmpty(find))
{
searchResults = titles.Where(t => t.ToLower().Contains(find.ToLower())).Select(p => p).ToArray();
}
else
{
searchResults = null;
}
TableView.ReloadData();
}
This search implementation uses LINQ to search the list of titles, saves the results in the searchResults field, and reloads the table view’s data. When this happens, the table view will display either the search results or the entire book list.
NavigationItem
Prior versions of iOS required developers to manually position the UISearchController‘s search bar in their application’s interface. In iOS 11, setting the SearchController property on a view controller’s NavigationItem places a search bar in the navigation bar. For example, in LargeTitlesViewController+Search.cs:
{
// …
NavigationItem.SearchController = search;
// …
}