首页 > 解决方案 > 在静态 UITableView 中动态替换单元格

问题描述

在我正在编写的应用程序中,我有一个使用故事板围绕 UITableView 构建的表单,其中包含 UITableViewController 中的静态单元格。该表有 6 行收集不同的信息位。第 0,3,4,5 行有 textfield/textview/labels 来收集/显示一些信息,第 1 行有一个带有十几个图标的 UICollectionView。第 2 行的高度为 50,但现在为空。

在此处输入图像描述

此设置运行良好,但我正在尝试添加一些功能,但我很难过。根据我在 UICollectionView(第 1 行)中选择的内容,我想在第 2 行加载多个不同单元格中的一个

例如,如果我点击第二个图标(血压),第 2 行中要加载的单元格将用于输入收缩压和舒张压值。如果我点击第三个图标(温度),第 2 行中要加载的单元格将用于输入温度等...

我已经在 UITableViewCell 的单独类文件和相应的 xib 文件中设计了单元格。我知道如何使用

   tableView.register(UINib(nibName: "myBPTableCell", bundle: nil), forCellReuseIdentifier: "myBPTableCell")

只是不确定将动态更新表的逻辑放在哪里。

   if eventTypeCollectionIndex == 4 {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myBPTableCell", for: indexPath) as! myBPdTableCell
        return cell
    }

我在想

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

但由于这个函数必须返回一个单元格,我不知道如何为第 2 行以外的任何内容返回预先存在的单元格

谢谢萨米

标签: iosswiftuitableview

解决方案


您可能希望在单元格中为索引方法中的行定义不同的情况。然后当用户点击一个按钮时,重新加载您想要更改的单元格。

您可以使用重新加载行self.tableView.reloadData()

例如:

var didTap = false

func buttonTapped() {
  didTap = true
  // Reload table
}

然后为单元格使用不同的笔尖:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  if didTap {
    // show new appearance
    let cell = tableView.dequeueReusableCell(withIdentifier: "myBPTableCell", for: indexPath) as! myBPdTableCell
    return cell
  } else {
    // show original
    let cell2 = tableView.dequeueReusableCell(withIdentifier: "myBPTableCell2", for: indexPath) as! myBPdTableCell2
    return cell2
  }
}

或者您可以更新同一个 nib 类的属性:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "myBPTableCell", for: indexPath) as! myBPdTableCell
  if didTap {
    // show new appearance
    cell.backgroundColor = .white
  } else {
    // show original
    cell.backgroundColor = .black
  }
  return cell
}

根据评论编辑:

您也可以执行以下操作,其中第 2 行有一个单元格,其他行有另一个单元格:

if indexPath.row == 2 {
  let cell = tableView.dequeueReusableCell(withIdentifier: "myBPTableCell", for: indexPath) as! myBPdTableCell

    if didTap {
       cell.backgroundColor = .white
    } else {
       cell.backgroundColor = .black
    }

    return cell
} else {
  let cell = tableView.dequeueReusableCell(withIdentifier: "myOtherCell", for: indexPath) as! myOtherCell
    return cell
}

推荐阅读