1

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.stack.imgur.com/rPHuy.jpg "NormalView"

https://i.stack.imgur.com/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!
}

}

Phil
  • 13
  • 3
  • Is there a reason you set text and image when not searching and just the text when searching? You need to assign the image like `UIImage(named : searchUnits[indexPath.row])` – D. Mika Jan 16 '19 at 18:54
  • Wow thanks guys..it worked – Phil Jan 16 '19 at 19:18

1 Answers1

0

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])
    }
Robin Bork
  • 297
  • 2
  • 8
  • Thanks, but it dont work. The problem is, that i fixed first the images with indexPath. first row, first image, second row second image and so on.... so when iam searchin, the first row shows me the image of the fifth element (when iam searchin for the fifth element e.g.) – Phil Jan 16 '19 at 19:15
  • @Phil Good to hear! Would you then please mark the answer as the correct one? Thanks! – Robin Bork Jan 16 '19 at 21:20