从自定义 tableView 单元格文本字段中获取数据

Get data from custom tableView cell text field

我有一个 table 视图,table 视图中的自定义 table 视图单元格,以及自定义 table 视图单元格中的一些文本字段。

我根据 table 视图单元格中的文本字段中的信息更新 class。

我能够使用 didDeselectRowAt 函数成功获取单元格文本字段中的数据来更新我的 class,但是,这不是正确的实现,因为它需要用户单击并取消选择文本字段所在的单元格,如果在编辑文本字段后更新 class 会更好。我搜索了 tableViews 的类似功能,但没有找到有效的功能。

在我的 CustomTableViewCell class 中,我还可以创建一个在编辑文本字段结束时执行的函数,但是这是在另一个 class 中,我不确定如何填充我的玩家 class 来自此功能。

这是 ViewController 中的代码:

public func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell

    for item in players {
        if item.uniqueRowID == indexPath.row {
            item.name = cell.textboxName.text!
        }
    }
}

我想做类似的事情,用自定义 table 视图单元格内的文本字段中的数据填充我的 'players' class,但我想要它在每个文本字段中完成编辑时发生,并且此代码在 customTableViewCell class.

中不起作用

不胜感激!

使用传递给单元格的模型对象怎么样?在单元内,可以在用户交互时进行任何更新。对象的编辑触发器保留在单元格内,可以立即生效。

这是一个人为的例子。

final class UIViewController: UITableViewDataSource {

  var players: [Player] = [] // Players set by something in the view controller.

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    guard let cell = tableView.cellForRow(at: indexPath) as? CustomTableViewCell else { fatalError() }

    cell.player = players[indexPath.row]

    return cell
  }
}

在单元格本身中:

final CustomTableViewCell: UITableViewCell, UITextFieldDelegate {

  var player: Player!

  weak var textField: UITextField!

  func textFieldDidEndEditing(_ textField: UITextField) {

    player.name = textField.text
  }
}

接下来,您可以选择使用 ViewModel 进一步抽象关系。