Peter Pik
Peter Pik

Reputation: 11193

Remove cells when searchBar text is above 0

i've created a tableView which i first did set to that it should use the filtered array if the searchController was active. However i want to first do it when the searchBar contain more than 0 characters. However this does not seem to work. Here is what i've done so far in cellForRowAtIndexPath

    if (count(self.teamSearchController.searchBar.text) > 0) {
        team = filteredTableData[indexPath.row] as Team
        cell.textLabel?.text = team.name as String

    } else {
        team = self.teamArray[indexPath.row] as Team
        cell.textLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 20)
        cell.textLabel?.text = team.name as String

    }

updateSearchResultsForSearchController

func updateSearchResultsForSearchController(searchController: UISearchController)
{



    filteredTableData.removeAll(keepCapacity: false)

    let searchPredicate = NSPredicate(format: "name CONTAINS[c] %@ OR shortname CONTAINS[c] %@", searchController.searchBar.text, searchController.searchBar.text)
    let array = (teamArray as NSArray).filteredArrayUsingPredicate(searchPredicate) as! [Team]
    filteredTableData = array

    self.tableView.reloadData()
}

Upvotes: 1

Views: 115

Answers (2)

Praveen Gowda I V
Praveen Gowda I V

Reputation: 9637

You should do the checking for length of search text in updateSearchResultsForSearchController

func updateSearchResultsForSearchController(searchController: UISearchController)
{

    if searchController.searchBar.text == "" {
        filteredTableData = self.teamArray      
    } else {
        filteredTableData.removeAll(keepCapacity: false)

        let searchPredicate = NSPredicate(format: "name CONTAINS[c] %@ OR shortname CONTAINS[c] %@", searchController.searchBar.text, searchController.searchBar.text)

        let array = (teamArray as NSArray).filteredArrayUsingPredicate(searchPredicate) as! [Team]
        filteredTableData = array
    }
    self.tableView.reloadData()
}

Update the code in cellForRowAtIndexPath as shown below, just have a check if the searchController is active or not

if (self.teamSearchController.active) {
    team = filteredTableData[indexPath.row] as Team

} else {
    team = self.teamArray[indexPath.row] as Team
    cell.textLabel?.font = UIFont(name: "HelveticaNeue-Light", size: 20)
}
cell.textLabel?.text = team.name as String

Upvotes: 1

Mundi
Mundi

Reputation: 80271

I think it is not good design to query the search bar in every table view cell. Instead, have only one array that the table view displays.

Whenever the search bar contents change, change the content of the array to be displayed in the table to the filtered array. Handle your edge case in the update method. I think the if statement you wrote should work fine.

Upvotes: 0

Related Questions