搜索栏未正确过滤

时间:2017-09-01 19:21:35

标签: ios swift filter searchbar

我的tableview中有一个搜索栏,但是当我最初点击搜索栏时,结果会消失。如果我转到另一个控制器并返回,搜索栏工作正常,点击栏时会显示所有结果。

以下是代码:

@IBOutlet weak var toolTable: UITableView!
@IBOutlet weak var searchForTool: UISearchBar!

var searchActive : Bool = false
{
    didSet {
        if searchActive != oldValue {
            toolTable?.reloadData()
        }
    }
}

typealias Item = (data: String, identity: String)

var filtered: [Item] = []
var items: [Item] = [
    (data: " Data1", identity: "A"),
    (data: " Data2", identity: "B")
]

override func viewDidLoad() {
    super.viewDidLoad()

    toolTable.delegate = self
    toolTable.dataSource = self

    searchForTool.delegate = self

}

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) {

    filtered = items.filter { item in
        item.data.localizedCaseInsensitiveContains(searchText)
    }

    searchActive = !filtered.isEmpty

    self.toolTable.reloadData()
}


override func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    if(searchActive) {
        return filtered.count
    }

    return items.count

}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! CustomCell

    if(searchActive){
        cell.toolLabel.text = filtered[indexPath.row].data
    } else {
        cell.toolLabel.text = items[indexPath.row].data
    }

    return cell
}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vcName: String
    if searchActive {
        vcName = filtered[indexPath.row].identity
    } else {
        vcName = items[indexPath.row].identity
    }
    let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
    self.navigationController?.pushViewController(viewController!, animated: true)

}

我确定它是一个简单的解决方案,我只是忽略它。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

阅读您的代码我看到:searchBarTextDidBeginEditingsearchActive设置为true。数据将根据didSet中的代码重新加载。然后调用tableView:numberOfRowsInSection并返回filtered.count,表示为0,因为它为空。这就是结果消失的原因。