Home > Software design >  indexPath.row is wrong after reloading table view
indexPath.row is wrong after reloading table view

Time:02-02

I am using the indexPath.row to detect the last cell in my data source. After the data source changes, I reload using tableView.reloadRows(at: [indexPath], with: .automatic). However, I am getting incorrect values for indexPath.row after doing this.

cellForRowAt indexPath: IndexPath) -> UITableViewCell

` let type = allDirections.directions.routes[indexPath.row].type

        switch type {
            case .walk:
                 ........

            case .bus:
                
                cell.configure(showStops: showStops) { [weak self] in
                        self?.allDirections.directions.routes[indexPath.row].stopsIsShown.toggle()
                    DispatchQueue.main.async {
                        self?.tableView.reloadRows(at: [indexPath], with: .automatic)
                    }
                }

                if indexPath.row == allDirections.directions.routes.count - 1 { cell.addEndLocationLabel() }
                if indexPath.row > 0 { cell.addPrevLine(color: color) }

                return cell
        }

`

End location label gets added randomly to other cells as well! Please help

CodePudding user response:

UITableView reuses cell views for efficiency. You have two statements that depend on a cell's row:

if indexPath.row == allDirections.directions.routes.count - 1 { cell.addEndLocationLabel() }
if indexPath.row > 0 { cell.addPrevLine(color: color) }

You need to undo the effects of these statements if the cell gets reused for a different row. For example:

if indexPath.row == allDirections.directions.routes.count - 1 {
    cell.addEndLocationLabel()
} else {
    cell.removeEndLocationLabelIfPresent()
}

if indexPath.row > 0 {
    cell.addPrevLine(color: color)
} else {
    cell.removePrevLineIfPresent()
}
  • Related