Search code examples
indexpathxcode10.1

xcode , indexPath, SearchBar


i have a Problem with my NavigationController and a searchbar with indexPath. I have a Tableview where i have a list of items. The items are 1. image and 1. image description(label) for each row.

Now i tried to paste a SearchBar for the List. It works pretty Well but when iam searching e.g. the second item of the list (AssaultGren.), the table shows me the wrong (first) image. Its because when iam searching the second item is the First item in the searchView.....Now i dont know how to fix it. Maybe someone can help me? Thanks guys

https://i.sstatic.net/rPHuy.jpg "NormalView"

https://i.sstatic.net/O5Gqe.jpg "SearchView"

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


    if searching{
        cell?.UnitName?.text = searchUnits[indexPath.row]
    } else {
        cell?.UnitName.text = units[indexPath.row]
        cell?.UnitBild.image = UIImage(named : units[indexPath.row])
    }

    return cell!
}

}


Solution

  • I think you forgot to set the correct image in case you are searching. Since the table view cells are being reused by iOS it keeps the image that was being set before, so you have to set it again. Try this:

    if searching{
            cell?.UnitName?.text = searchUnits[indexPath.row]
            cell?.UnitBild.image = UIImage(named : searchUnits[indexPath.row])
        } else {
            cell?.UnitName.text = units[indexPath.row]
            cell?.UnitBild.image = UIImage(named : units[indexPath.row])
        }