且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在tableview单元格中编辑文本字段时重新加载所有tableview单元格 - iOS Swift

更新时间:2022-11-23 08:27:08

我会避免重新加载表格视图,这样就不会打扰你的第一响应者状态文本。您可以(1)仅插入和删除更改的内容,或者(2)重新调整需要更新的单元格。

I would avoid reloading the table view at all so that you don't disturb the first responder status of your text. You could either (1) insert and delete only what's changed or (2) redecorate cells that need updating.

因此,不需要调用 myTableView.reloadData(),找出需要的索引路径添加或删除并调用适当的方法。

So, instead of calling myTableView.reloadData(), figure out which index paths need to be added or removed and call the appropriate methods.

myTableView.insertRows(at: newIndexPaths, with: .automatic)
myTableView.deleteRows(at: oldIndexPaths, with: .automatic)



2。重新装修



这需要一种更模块化的方法来确定如何使单元格出列。而不是这样做:

2. Redecorating

This requires a more modular approach to how you are dequeuing cells. Instead of doing this:

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]
}

稍后您可以重新装修,即更新单元格的内容和配置,而无需重新加载并干扰第一响应者状态:

That way later on you can redecorate, i.e. update the content and configuration of the cells without reloading and disturbing the first responder status:

for cell in myTableView.visibleCells {
    if let indexPath = myTableView.indexPath(for: cell) {
        decorate(cell: cell, at: indexPath)
    }
}