【问题标题】:Get data from custom tableView cell text field从自定义 tableView 单元格文本字段中获取数据
【发布时间】:2018-04-10 11:15:01
【问题描述】:

我有一个 tableView、tableView 内的自定义表格视图单元格以及自定义表格视图单元格内的一些文本字段。

我根据表格视图单元格中的文本字段中的信息更新一个类。

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

在我的 CustomTableViewCell 类中,我还能够创建一个在文本字段编辑结束时执行的函数,但是这是在另一个类中,我不确定如何从该函数填充我的玩家类。

这是 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!
        }
    }
}

我想做与此类似的事情,用自定义表格视图单元格内的文本字段中的数据填充我的“玩家”类,但我希望在每个文本字段中完成编辑时发生这种情况,并且这段代码在 customTableViewCell 类中不起作用。

我们将不胜感激!

【问题讨论】:

  • 您需要创建一个从您的单元返回到您的视图控制器的委托协议
  • @Paulw11 是的,但我怎么知道信息来自哪个单元格? (indexPath)
  • 在调用委托方法时让单元格通过self

标签: ios swift uitableview uitextfield


【解决方案1】:

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

这是一个人为的例子。

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 进一步抽象关系。

【讨论】:

  • 没问题@VladBarash,这是一个有趣的挑战。 :)
  • 谢谢。即使在使用 Realm 时也能像魅力一样工作?
猜你喜欢
  • 1970-01-01
  • 2015-12-27
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 2012-05-18
  • 2020-05-23
相关资源
最近更新 更多