【问题标题】:Swift UITableView didSelectRowAtIndexPath bugSwift UITableView didSelectRowAtIndexPath 错误
【发布时间】:2015-03-07 23:07:30
【问题描述】:

我有一个隐藏了字幕的 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 上的可见表的高度。当我在模拟器中以 4s 运行它时,它大约每 8 个单元格。但我不知道除了“visibleCells”还能怎么做?但这很奇怪,因为它是整个表格 - 一直向下,每 12 个单元格显示它的副标题...

感谢您的帮助

【问题讨论】:

    标签: ios swift uitableview didselectrowatindexpath detailtextlabel


    【解决方案1】:

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

    【讨论】:

    • 谢谢 - 我不知道如何定义 prepareForReuse() 但我用“let cell = tableView.dequeueReusableCellWithIdentifier”覆盖 func tableView(tableView: UITableView, cellForRowAtIndexPath" 所以我添加了“ cell.detailTextLabel?.hidden = true" ,它似乎已经解决了这个问题。这是一个好的解决方案吗?我的意思是,我知道它正在工作,但我不知道这是否是一种不好的方法,性能- 与“prepareForReuse()”相比——也许这是相同的结果?再次感谢
    • 这也可以。性能方面,它没有任何区别。在cellForRowAtIndexPath 中,您返回一个配置的单元格。我更喜欢让单元子类处理它的属性,并在cellForRowAtIndexPath 中尽可能少地做。但这是一个品味问题。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-17
      • 2012-01-14
      • 2011-11-08
      • 1970-01-01
      • 2014-12-31
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      相关资源
      最近更新 更多