Search code examples
iosswiftuitableviewdidselectrowatindexpathdetailtextlabel

Swift UITableView didSelectRowAtIndexPath bug


I have a UITableView with the subtitles hidden but set up where when someone selects a cell it shows that cell's subtitle. This works fine except that after tapping any cell to reveal its subtitle if you scroll down you will find that every 12 cells have their subtitle unhidden (as well as the one it was supposed to reveal). Here is the code I'm using in didSelectRowAtIndexPath:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    for cell in tableView.visibleCells() {
        cell.detailTextLabel??.hidden = true
    }

    var cell = tableView.cellForRowAtIndexPath(indexPath)
    cell?.detailTextLabel?.hidden = false


}

I'm sure this is related to ".visibleCells()" since every 12 cells is about the height of my visible table on my iPhone 6 Plus. When I run it on a 4s in the simulator it's about every 8 cells. But I'm not sure how else to do it besides 'visibleCells'? But it's strange because it's the whole table - all the way down, every 12 cells is showing its subtitle...

thanks for any help


Solution

  • UITableView reuses its cells. So the cell for row a row you clicked on (unhidden the subtitle) may be used for row another row. The solution is to define prepareForReuse() method in the UITableViewCell subclass (or make the subclass if you do not have one) and hide the subtitle again there.