UITableView indexPath changing while scrolling

In my Table View I have the label text set to a different colour if the name is in the Flagged Array (flaggedNames). The correct cell labels turn red but as I scroll the text of other labels are also red. This changes as I scroll.


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)

        let name = names[indexPath.row]

        cell.textLabel?.text = name


        if flaggedNames.contains(meterNumber) {

            cell.textLabel?.textColor = .systemRed

        }

        return cell

    }

    

Answered by minnit in 689204022

Cells can be reused, which can lead to such problems. To this end, you should specify the text color of the normal label in the 'else' statement.

if flaggedNames.contains(meterNumber) {
    cell.textLabel?.textColor = .systemRed
} else { 
    cell.textLabel?.textColor = .black
}

You are using meterNumber which is not defined in your shown code. Usually, having other variables than data source can easily cause issues as you describe. Also, you are setting textColor to .systemRed, but there is no code which changes textColor to the normal color, please do not forget that cells are reused, the textColor of the cell dequeued is not known. Anyway, to find how to fix, you may need to show more context.

Accepted Answer

Cells can be reused, which can lead to such problems. To this end, you should specify the text color of the normal label in the 'else' statement.

if flaggedNames.contains(meterNumber) {
    cell.textLabel?.textColor = .systemRed
} else { 
    cell.textLabel?.textColor = .black
}

Sorry that was a typo in my question. “meterNumber” is supposed to be “name”

UITableView indexPath changing while scrolling
 
 
Q