Swift UITableView didSelectRowAtIndexPath 错误

Swift UITableView didSelectRowAtIndexPath bug

我有一个隐藏了字幕的 UITableView,但是设置了当有人选择一个单元格时它会显示该单元格的字幕。这工作正常,除了在点击任何单元格以显示其副标题后,如果您向下滚动,您会发现每 12 个单元格的副标题都未隐藏(以及它应该显示的那个)。这是我在 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


}

我确定这与“.visibleCells()”有关,因为每 12 个单元格大约是 iPhone 6 Plus 上可见 table 的高度。当我 运行 它在模拟器中的 4s 上它大约每 8 个单元格。但我不确定除了 'visibleCells' 还能怎么做?但这很奇怪,因为它是整个 table - 一直往下,每 12 个单元格显示其副标题...

感谢您的帮助

UITableView 重用了它的单元格。因此,您单击的一行的单元格(取消隐藏字幕)可能用于另一行。 解决方案是在 UITableViewCell 子类中定义 prepareForReuse() 方法(如果没有,则创建子类)并再次隐藏字幕。

将该数据源的方法添加到您的控制器。应该工作正常。

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

    return cell
}