如何重新加载所有的tableview单元格,同时在tableview单元格中编辑文本字段 – iOS Swift
为了清晰,我有一个包含textfield
的顶视图的UIView Controller
。 我也有一个tableview
下面,每行包含1个textfield
。
问题:当我"didEndEditing"
任何文本字段,这意味着在顶视图和在tableview我想保存这些信息到核心数据和重新加载tableview
。
这完美的作品, 除了! 当我select一个文本字段(任何地方)input一个值,然后从一个文本字段中select,select另一个文本字段。 这导致键盘卡住,永远不会消失。
我已经诊断出这是因为当"DidEndEditing"
被调用时,由于单元被重新加载,我失去了对刚刚select的文本字段的引用(键盘已经启动)。
有没有人遇到过这个? 有没有人find一个优雅的解决scheme,重新加载数据到tableview cell
同时select其中的textfield
?
编辑:我已经尝试将reloadData()
移动到"DidBeginEditing"
的"DidBeginEditing"
函数,并成功地获得了select指示器出现,但再次键盘没有参考,即使我调用成为第一响应者后tableView.relaodData()
我会避免重新加载表视图,以便您不要打扰您的文本的第一响应者状态。 您可以(1)只插入和删除已更改的内容或(2)重新整理需要更新的单元。
1.插入和删除
所以,而不是调用myTableView.reloadData()
,找出哪些索引path需要添加或删除,并调用适当的方法。
myTableView.insertRows(at: newIndexPaths, with: .automatic) myTableView.deleteRows(at: oldIndexPaths, with: .automatic)
2.重新装修
这就需要一个更模块化的方法来清除细胞。 而不是这样做:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) cell.data = dataArray[indexPath.row] return cell }
做这个:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) decorate(cell, at: indexPath) return cell } func decorate(_ cell: UITableViewCell, at indexPath: IndexPath) { cell.data = dataArray[indexPath.row] }
这样以后你可以重新装修 ,也就是更新单元格的内容和configuration,而不用重新加载和干扰第一响应者的状态:
for cell in myTableView.visibleCells { if let indexPath = myTableView.indexPath(for: cell) { decorate(cell: cell, at: indexPath) } }
你有没有尝试存储的索引path之前重新加载你的tableview,并使用它来find你的单元格,并设置其中的文本字段作为第一响应者重新加载后?