【发布时间】: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