我创建了一个tableView,我首先将其设置为如果searchController处于 Activity 状态,则应使用过滤后的数组。但是,当searchBar包含超过0个字符时,我想先执行此操作。但是,这似乎不起作用。这是我到目前为止在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()
}
最佳答案
您应该检查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()
}
如下所示更新
cellForRowAtIndexPath
中的代码,只需检查searchController是否处于 Activity 状态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