当searchBar文本高于0时删除单元格

时间:2015-05-13 22:39:39

标签: ios uitableview swift uisearchcontroller

我已经创建了一个tableView,我首先设置它,如果searchController处于活动状态,它应该使用过滤后的数组。但是,当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()
}

2 个答案:

答案 0 :(得分:1)

您应该在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是否处于活动状态

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

答案 1 :(得分:0)

我认为在每个表视图单元格中查询搜索栏并不是一个好的设计。相反,只有一个表视图显示的数组。

每当搜索栏内容发生更改时,将要在表中显示的数组的内容更改为已过滤的数组。在update方法中处理边缘大小写。我认为你写的if语句应该可以正常工作。