【问题标题】:Ios show/hide views inside a tableview cellios在tableview单元格中显示/隐藏视图
【发布时间】:2017-11-01 04:30:26
【问题描述】:

我有一个带有自定义单元格的表格视图。下图显示了我的 tableview 单元格的视图层次结构。

向 tableview 添加行时,我使用以下代码隐藏了“检查图像”图像视图。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell

            cell.checkImage.isHidden = true

        return cell
    }

当点击一行时,我将再次显示 imageview。下面是代码

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell

        cell.checkImage.isHidden = false
    }

但问题是当我点击一行时没有任何反应。系统执行cell.checkImage.isHidden = false 代码行,但没有出现图像视图。它仍然是隐藏的。有人可以告诉我我在这里做错了什么吗?

【问题讨论】:

  • 点击该行后请重新加载您的tableview
  • 你不能那样做。您需要在某处更新选中/未选中状态(我建议使用Set<IndexPath>),然后在cellForRowAt 中检查 - 在didSelectRowAt 中,您在Set 中切换选中/未选中状态,然后重新加载受影响的细胞。
  • @Nazmul Hasan 重新加载 tableview 对我不起作用
  • @udi 重新加载表格视图的位置
  • @Paulw11 你能解释一下吗?

标签: ios swift uitableview uistackview


【解决方案1】:

您无法在自己的单元格中跟踪单元格检查状态;单元格对象只是您数据的一个视图,当表格视图滚动时,单元格将被重用。

我建议使用Set<IndexPath>。在您的cellForRowAt 中,您可以检查集合的内容以确定是否应隐藏复选标记:

var checked = Set<IndexPath>()

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "accountCell", for: indexPath) as! AccountsTableViewCell

    cell.checkImage.isHidden = self.checked.contains(indexPath)

    return cell
}

在您的 didSelectRowAt 中,您只需切换设置的成员资格并重新加载行

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if self.checked.contains(indexPath) {
        self.checked.remove(indexPath) 
     } else {
        self.checked.insert(indexPath)
     }

    tableView.reloadRows(at:[indexPath], with:.fade)
}

【讨论】:

  • 'self.checked.contains(indexPath) ? self.checked.remove(indexPath) : self.checked.insert(indexPath)' 给我一个编译错误。
  • @udi 你的 swift 版本是什么?
  • @NazmulHasan swift 4
  • 编译错误是:结果值在'? :' 表达式的类型不匹配 'IndexPath?'和'(插入:布尔,memberAfterInsert:IndexPath)'
  • 对不起。修复了
【解决方案2】:

您必须管理您的数组(数据源)!当您单击行时,更新该索引的数组并重新加载表视图。

例子:

您的数组应该有一些标志,例如 isChecked 将其值从 true 切换为 false,反之亦然。

在您的cellForRowAtIndexPath 中检查此标志并根据该标志显示或隐藏您的图像!

【讨论】:

  • 您的解决方案也有效。不幸的是,我只能接受一个答案。但感谢您的支持。
【解决方案3】:

首先确定你的

 tableview.delegate = self

第二件事在索引处选择行使用该代码

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let cell = tableView.cellForRow(at: indexPath) as! AccountsTableViewCell


    cell.checkImage.isHidden = false
}

【讨论】: