代码之家  ›  专栏  ›  技术社区  ›  Ivan Cantarino

UITableView中的重复单元格

  •  0
  • Ivan Cantarino  · 技术社区  · 6 年前

    我在这里读过一些关于为什么会发生这种情况的解释,但我无法找到解决方案,这可能非常简单。

    我有一个 UITableViewController 它有两个部分,每个部分有20行。

    我想添加一个 UISwitcher 在第二行中,我实现了以下内容:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? SettingsCell else {
            return UITableViewCell()
        }
        switch indexPath.row {
        case 2: cell.addSwitcher()
        default: break
        }
        return cell
    }
    

    在我上下滚动之前,一切都按预期工作,过一段时间后,我会在每一行中都有切换器。

    dequeueReusableCell 还是我在这里丢了什么东西?

    这是我的 addSwitcher() 功能

    public func addSwitcher() {
        accessoryView = switcher
        switcher.addTarget(self, action: #selector(switcherDidChange(switcher:)), for: .valueChanged)
        hasSwitcher = true
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Shehata Gamal    6 年前

    当然,这是因为单元格排样的缘故,当您为该单元格设置并滚动时,下面显示的其他单元格将从中获取相同的单元格。 dequeueReusableCell ,因此需要将nil分配给 accessoryView 清除以前分配给它的任何视图

    let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SettingsCell
    cell.accessoryView = nil
    

    您还可以覆盖 prepareForReuse

    推荐文章