Search Bar is not filtering properly

145 Views Asked by At

I have a search bar in my tableview, but when I initially click on the search bar, the results disappear. If I segue to another controller, and come back, the search bar works fine, with all the results showing when the bar is clicked.

Here is the code:

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

}

I'm sure its some simple solution, I'm just overlooking it.

Any help would be greatly appreciated.

1

There are 1 best solutions below

3
On BEST ANSWER

Reading your code I see that: searchBarTextDidBeginEditing sets searchActive to true. The data will be reloaded as per the code in didSet. tableView:numberOfRowsInSection is then called and filtered.count is returned, meaning 0 as it's empty. That's why results disappear.