当编辑一个单元格时,Swift tableview会更改随机单元格的值 [英] Swift tableview changes the value of a random cell when one cell is edited

查看:94
本文介绍了当编辑一个单元格时,Swift tableview会更改随机单元格的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很长的文本字段列表,所以我使用的是tableView。

I have a long list of textfields so I am using a tableView.

这就是屏幕的样子

当我在其中一个单元格的文本字段中插入一些文本时向下滚动其他一些单元格获得相同的文本字段值。我不知道为什么会这样。

When I insert some text in a textfield in one of the cells and scroll down some other cells get the same textfield value. I have no idea why this would happen.

这是我现在的代码:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cellId", for: indexPath) as! RelatieToevoegenCell
    cell.label.text = items[indexPath.row]
    cell.textfield.placeholder = items[indexPath.row]
    return cell
}


推荐答案

您的主要问题是您将数据保存在Views(UITableVieCell)中。

Your main problem is that you are keeping your data inside Views (UITableVieCell).

UITableView重复使用单元格以优化性能 - 所以即使你的表中有1milion行,内存中只有少数UITableViewCells(通常在屏幕上可见的数量) )。

Cells are reused by UITableView to optimize performance - so even if you have 1milion rows in your table, only few UITableViewCells are in memory (as many as are visible on the screen usually).

当你打电话给 dequeueReusableCell 时,它需要一个已经存在的单元并重复使用它。

When you are calling dequeueReusableCell it takes one of already existing cells and reuse it.

要解决此问题,您需要将数据单独保存在数组中并在其中保留修改后的文本。
然后你需要修改你发布的代码,每次从你的dataSource配置UITableView时都要获取数据。

To solve this problem you need to keep your data separately in an Array and keep modified texts there. Then you need to modify code you posted, to take data every single time you configure UITableView from your "dataSource".

另外一个好的实践是重置UITableViewCell重用时,您可以通过在 prepareForReuse 中添加编码来实现此目的 - 但这是可选的,因为文本将始终从您的数据源设置。

Also a good pratcice is to reset UITableViewCell when it's reused, you can do this by adding coding inside prepareForReuse - but that's optional, as text will be set from your data source anyways.

我还建议您在开始编码之前阅读此内容 - 这将有助于理解UITableView适用于iOS:

I would also recommend to read this before you start coding further - it will allow to understand how UITableView works on iOS:

https://developer.apple.com/library/content/documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells。 HTML#// apple_ref / DOC / uid / TP40007451-CH7-SW1

这篇关于当编辑一个单元格时,Swift tableview会更改随机单元格的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆