I have a UITableViewController that that use a simple SearchBar for filtering result. I'm using an array of candies with name and category and I'm using these categories as options for the scope bar of my SearchBar. I have an utility function to apply the filter:
func filterContentForSearchText(searchText: String, scope: String = "All") {
// Filter the array using the filter method
self.filteredCandies = self.candies.filter(){( candy: Candy) -> Bool in
let categoryMatch = (scope == "All") || (candy.category == scope)
let stringMatch = candy.name.rangeOfString(searchText, options: NSStringCompareOptions.CaseInsensitiveSearch)
return categoryMatch && (stringMatch != nil)
}
}
I call this function in the searchDisplayController:shouldReloadTableForSearchScope:
method and in the searchDisplayController:shouldReloadTableForSearchString:
method.
If I put some text in the SearchBar everything works, even when I choose a scope from the scope bar. The problem is that when I clear the text (or when I choose a scope without put any text) the filter doesn't applied. With some debugging I saw that the array is well filtered when the tableView:cellForRowAtIndexPath:
is called but the tableView simply show all the elements, not the filtered ones.
The functionality of the UISearchDisplayController
is to only display the searchResultsTableView
when there is text in the search bar. The best way to work around this that I have found is to create your own segmented controller to use as a scope bar and filter the actual data source for your tableview by the scope and then filter that by search text when a search string is entered.
Sorry!