如何同时更新每个自定义tableview单元格数据?

How to update each custom tableview cell data at the same time?

我正在使用 Xcode 8.2.1 和 Swift 3. 我有一个包含 UITextView 的自定义 UITableViewCell。当我输入 textView 时,自定义单元格会自动增长。这部分工作正常。当我输入特定单元格时,我还想用相同的数据更新我的其他单元格。例如:

当我在第 5 个单元格中键入文本时,会自动在第 11、15 和 18 单元格中输入相同的数据。这些细胞也必须自动生长。我已将数据添加到数组的特定索引中。但它没有反映在 tableView 中。我如何实现此功能?

请检查我目前已实现的以下代码。此 updateCellHeight 方法是自定义委托方法。当用户输入 textView.

时调用此方法
func updateCellHeight(indexPath: IndexPath, comment: String) {

    let currentCellLyricVal = self.traduzioneArray[indexPath.row]["rics"]
    tempIndexArray.removeAll()

    for (index,element) in traduzioneArray.enumerated() {

        let lyricVal = element["rics"]
        if currentCellLyricVal == lyricVal {
            tempIndexArray.append(index)
        }
    }
    for index in tempIndexArray {
        self.traduzioneArray[index]["ione"] = comment
        self.lyricsTableView.beginUpdates()
        self.lyricsTableView.endUpdates()
    }
}

func textViewDidChange(_ textView: UITextView) {
    self.delegate.updateCellHeight(indexPath: self.cellIndexPath, comment: textView.text)
}

首先,从故事板或在您的 tableView 单元格中 class 设置文本视图 NumberOfLines = 0 .

行代表的高度有

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

在您的 viewdidLoad 中添加这些行:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140

在tableViewController中

 func updateCellHeight(indexPath: IndexPath, comment: String) {

    let currentCellLyricVal = self.traduzioneArray[indexPath.row]["rics"]
    tempIndexArray.removeAll()

    for (index,element) in traduzioneArray.enumerated() {

        let lyricVal = element["rics"]
        if currentCellLyricVal == lyricVal {
            tempIndexArray.append(index)
        }
    }
    for index in tempIndexArray {
        self.traduzioneArray[index]["ione"] = comment
    }
      tableView.reloadRows(at: [IndexPath(row: 11, section: 1),IndexPath(row: 13, section: 1)], with: UITableViewRowAnimation.none)
}

通过将线条设置为 0 和自动标注高度,单元格会自动调整大小。还请验证您是否在 cellForRow 方法 中将自定义单元格委托给了自己。

用新数据更新数据集后。使用更新的数据集重新加载特定单元格。

func updateCellHeight(indexPath: IndexPath, comment: String) {
        DispatchQueue.main.async {
            let currentCellLyricVal = self.traduzioneArray[indexPath.row]["rics"]
            tempIndexArray.removeAll()

            for (index,element) in traduzioneArray.enumerated() {

                let lyricVal = element["rics"]
                //You have to skip the current cell. by checking index != indexPath.row
                if currentCellLyricVal == lyricVal, index != indexPath.row {
                    tempIndexArray.append(index)
                }
            }

            for index in tempIndexArray {
                self.traduzioneArray[index]["ione"] = comment

                let updatedIndexPath = IndexPath(row: index, section: indexPath.section)
                  if let visibleCellIndexPaths = tableView.indexPathsForVisibleRows  {
                       if visibleCellIndexPaths.contains(updatedIndexPath) {
                            tableView.reloadRows(at: [updatedIndexPath], with: .automatic)
                       }
                  }
            }
        }
    }

注意:如果修改后的数据集单元格可见,那么我们只需要重新加载特定的单元格。

我认为自动数据输入的问题在于重新加载单元格会导致 resignFirstResponder() 调用。

这似乎很合乎逻辑,因为在重新加载数据时,您实际上放弃了一些单元格,并通过 cellForRowAt: 向 table 视图询问新单元格。旧的可能不一样,所以它们 resignFirstResponder().

更新单元格文本的一种方法是直接更改单元格内容。您可以对文本视图内容执行此操作。不幸的是,对于单元格高度,无法在不触发 heightForRowAt:.

的情况下直接更改单元格

更新 2:iOS 8+ 在 table 视图上结合了直接单元格操作和 AutomaticDimension 的解决方案。
完美地为 UITextView 工作。检查下面的更新。这是最终结果的样子:

更新 1:添加了直接单元格操作的代码示例

使用简单模型保存table 查看数据:

// Simple model, for the example only
class Model {
    // The value of the text field
    var value: String?
    // The type of the cell
    var type: CustomCell.CellType = .typeA

    init(value: String) {
        self.value = value
    }

    init(value: String, type: CustomCell.CellType) {
        self.value = value
        self.type = type
    }
}

// Init the model.
var tableData = [
    Model(value: "Cell Type A", type: .typeA),
    Model(value: "Cell Type B", type: .typeB),
    Model(value: "Cell Type B", type: .typeB),
    Model(value: "Cell Type A", type: .typeA),
    Model(value: "Cell Type B", type: .typeB)]

并像这样委托:

// Delegate to update visible cells in the table view when text field value change.
protocol TextChangeDelegate {
    func textChangedAtCell(_ cell: CustomCell, text: String?)
}

然后初始化您的自定义单元格:

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

    // Will crash if identifier is not registered in IB
    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomCell

    // For this to work you need to update the model on each text field text change
    cell.textValue.text = tableData[indexPath.row].value
    cell.index = indexPath.row
    cell.type = tableData[indexPath.row].type
    cell.textChangeDelegate = self

    return cell
}

在自定义单元格中:

class CustomCell: UITableViewCell {

    // The type of the cell. Cells with same type will be updated simultaneously.
    enum CellType {
        case typeA
        case typeB
    }

    // Very simple prototype cell with only one text field in it
    @IBOutlet weak var textValue: UITextField!

    // Default type
    var type = CellType.typeA
    // Index in the model. Not optional (or other special assumptions on initial value)
    // for simplicity of the example.
    var index = 0
    var textChangeDelegate: TextChangeDelegate?
}

extension CustomCell: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        // Assume we will return true. Any logic could appear here.
        // If we need to return false, don't call the delegate method.
        let result = true

        if result {
            let nsString = textField.text as NSString?
            let newString = nsString?.replacingCharacters(in: range, with: string)
            print("New: \(newString ?? "(nil)")")

            textChangeDelegate?.textChangedAtCell(self, text: newString)
        }

        return result
    }
}

这是如何在具有直接单元格访问的视图控制器中实现 TextChangeDelegate,即无需重新加载数据:

extension ViewController: TextChangeDelegate {

    func textChangedAtCell(_ cell: CustomCell, text: String?) {

        // Only visual update. Skip the cell we are currently editing.
        for visibleCell in tableView.visibleCells where visibleCell != cell {
            if let currentCell = visibleCell as? CustomCell,
                tableData[currentCell.index].type == cell.type {
                    currentCell.textValue.text = text
            }
        }

        // Update the model (including invisible cells too)
        for (index, data) in tableData.enumerated() where data.type == cell.type {
            tableData[index].value = text
        }

        // Avoid reloading here, as this will trigger resignFirstResponder and you will
        // have issues when jumping from text field to text field across cells.
    }
}

您现在可以在具有相同 CellType 的所有单元格上同时进行文本更新。此示例使用 UITextField(检查 UITextView 的 UPDATE2)。

UPDATE2 放在这里。带有同时文本和高度调整的 UITextView 的单元格。

使用上一个示例中的模型和控制器(因为您将使用新的单元格,所以需要稍作改动)。 利用 UITableViewCell 并将 UITextView 放入其中。在 AutoLayout 中将约束设置为文本视图:

记得禁用滚动和弹跳到文本视图(否则你将没有自动高度)。 不要忘记 link textView 的委托给 UITextViewCell 子类。

然后在单元格中,使用

func textViewDidChange(_ textView: UITextView) {
    self.textChangeDelegate?.textChangedAtCell(self, text: textView.text)
}

然后,超级重要,在ViewController的viewDidLoad中,添加这两个设置

tableView.estimatedRowHeight = 50
tableView.rowHeight = UITableViewAutomaticDimension

并注册单元格:

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

最后,将此代码添加到 UPDATE1 的 TextChangeDelegate 实现中以执行实际的高度更新技巧:

func textChangedAtCell(_ cell: UITableViewCell, text: String?) {

    <code from UPDATE 1 goes here>

    tableView.beginUpdates()
    tableView.endUpdates()
}

尽情享受吧!

每次需要更新单元格时使用此代码:

func updateCellHeight(indexPath: IndexPath, comment: String) {

  //update dataModel according to new text
  ...
  //then reload visible tableview rows
  //pay atttention to beginUpdates endUpdates methods.
  //This do the trick)

  tableView.beginUpdates()
  tableView.reloadRows(at: indexPathsForVisibleRows ?? [], with: .none)
  tableView.endUpdates()

 }