Francesco Frascà
Francesco Frascà

Reputation: 186

UISearchDisplayController doesn't reload data when searching only by scope

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.

Upvotes: 0

Views: 792

Answers (2)

monotreme
monotreme

Reputation: 582

I accomplished this by reloading my tableview from the delegate method.

func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
    println("Scope Changed")
    updateSearchResultsForSearchController(searchController)
}

That last function should contain code for resetting your filter / remaking your array / fetching all objects from coredata (if that's what you're doing) AND reloading your tableView.

Upvotes: 0

AnthonyMDev
AnthonyMDev

Reputation: 1506

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!

Upvotes: 1

Related Questions