【问题标题】:UITableViewCell - Get UITextField values in dynamic tableviewUITableViewCell - 在动态表格视图中获取 UITextField 值
【发布时间】:2018-07-25 13:20:25
【问题描述】:

问题是,我已经找到的大多数解决方案都涉及使用self.myTableView.cellForRow(at: index) as! 方法。 问题是如果你有一个大的 UITableView,单元格最终会被重用,并且你会丢失引用。

另一种方法涉及使用textFieldDidEndEditing(_ textField: UITextField),但我不知道这是否是最好的优雅解决方案。

这是我正在使用的一些代码:

protocol TableViewCompatible {

    var reuseIdentifier: String { get }

    func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> UITableViewCell

}

class NameCellDTO: TableViewCompatible {

    var reuseIdentifier: String {
        return "NameCell"
    }

    var name: String?
    var placeHolder: String

    init(name: String? = nil, placeHolder: String) {
        self.name = name
        self.placeHolder = placeHolder
    }

    func cellForTableView(tableView: UITableView, atIndexPath indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: self.reuseIdentifier, for: indexPath) as! NameCell
        cell.configureWithDTO(self)
        return cell
    }
}

DTO 创建:

let nameCell = NameCellDTO(name: "Test", placeHolder: "attributes.user.first_name".localized())

我有一个包含一些 TableViewCompatible DTO 的数组 和 cellForRow :

func cellForRowAt(tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let item = items.object(index: indexPath.row) else {
        return UITableViewCell()
    }
    return item.cellForTableView(tableView: tableView, atIndexPath: indexPath)
}

【问题讨论】:

  • 您需要将应用程序的数据源保存在某个集合中。这样您就可以在重复使用时更新单元格。
  • 你是使用自定义的UITableViewCell 子类还是简单的UITableViewCell
  • 更新单元格内的值是有意义的,但我如何获取 UITextField 内的值?我的意思是,在用户已经更改了文本之后? @rv7284
  • 您能否发布一些代码来展示您到目前为止所做的尝试?我的直觉是,这应该与您的数据模型真正相关:当单元格被编辑时,模型应该被更新,然后您从那里检索您需要的数据。
  • 自定义UITableViewCell@Ladislav

标签: ios swift uitableview uitextfield


【解决方案1】:

你可以试试

var arr = [String](repeating: "", count: countOfRows)

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

    let cell =  ///

    cell.myTextF.delegate = self

    cell.myTextF.tag = indexPath.row

    cell.myTextF.text = arr[indexPath.row]
} 

func textFieldDidEndEditing(_ textField: UITextField) {

    arr[textField.tag] = textField.text!

}

【讨论】:

  • 好主意,我最终向我的 DTO 添加了一个属性值:var value: String = "" 并使用 value Changed 方法,只是为了避免继承 NSObject cell.textField.addTarget(self, action: #selector(textFieldDidChange(_:)), for: .editingChanged) ``` @objc func textFieldDidChange(_ textField : UITextField) { value = textField.text ?? "" }```,他们访问 DTO 以获取值
猜你喜欢
  • 2012-03-23
  • 1970-01-01
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多