1

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

Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358
Tommy Draughn
  • 179
  • 1
  • 12

2 Answers2

2

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.

diederikh
  • 25,221
  • 5
  • 36
  • 49
  • Thank you - I wasn't sure how to define prepareForReuse() but I had my " override func tableView(tableView: UITableView, cellForRowAtIndexPath" with "let cell = tableView.dequeueReusableCellWithIdentifier" so I added "cell.detailTextLabel?.hidden = true" to it and it seems to have fixed the issue. Is that a good solution? I mean, I know it's working but I don't know if this is a bad way of doing it, performance-wise compared to "prepareForReuse()" - maybe this is the same results anyway? Thanks again – Tommy Draughn Mar 07 '15 at 23:29
  • That will work as well. Performance wise it does not make a difference. In `cellForRowAtIndexPath` you return a configured cell. I prefer to have the cell subclass handle its properties and do as little as possible in `cellForRowAtIndexPath`. But that is a matter of taste. – diederikh Mar 07 '15 at 23:36
1

Add that dataSource's method to your controller. Should work fine.

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) {
    var identifier = "cellIdentifier"
    var cell = tableView. dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath)
    cell.detailTextLabel?.hidden = true

    return cell
}
Bartłomiej Semańczyk
  • 59,234
  • 49
  • 233
  • 358