使用搜索栏的问题

时间:2017-12-02 09:51:33

标签: ios swift uisearchbar

我正在尝试在我的某个屏幕中实现搜索功能。这是发布的代码......

func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
    searchActive = true;
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
    searchActive = false;
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    searchActive = false;
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

    if searchText != "" {
        // Filter the results
        searchActive = true
//allTheData is an object of an array of struct
        filtered = self.allTheData.filter { _ in (searchText.lowercased().contains(searchText.lowercased())) }


        if(filtered.count == 0){
            searchActive = false;
        } else {
            searchActive = true;
        }
        self.tableView.reloadData()
    }}

cellForRow中的代码为:

    if(searchActive){

        let filtObj = filtered[indexPath.row]

        cell.nameLabel.text = filtObj.customer_name
        cell.amtLabel.text = "\(filtObj.total_sales)"
    } else {
        let dataObj = allTheData[indexPath.row]
        cell.nameLabel.text = dataObj.customer_name
        cell.amtLabel.text = "\(dataObj.total_sales)"
    }

numberOfRows中的代码为:

 if(searchActive) {
            return filtered.count
        }

        return allTheData.count

但搜索没有发生。不知道是什么原因。希望有人能帮忙......

1 个答案:

答案 0 :(得分:1)

您的过滤器逻辑错误

filtered = self.allTheData.filter { $0.lowercased().contains(searchText.lowercased()) }