0

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

this is how the screen looks like

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.

This is my code now:

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
}
pacification
  • 5,838
  • 4
  • 29
  • 51
  • How do you handle the editing of the textfield? Please provide some more context. – Dávid Pásztor Sep 04 '17 at 14:38
  • @DávidPásztor at the moment I am not doing anything with the textfields, I just type in one of them and other textfields in differrent cells get the same text when I scroll down – Roman Haroyan Sep 04 '17 at 14:40

2 Answers2

2

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

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).

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

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".

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.

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

Grzegorz Krukowski
  • 18,081
  • 5
  • 50
  • 71
0

Basically, you have to get and store the values in view-controller because due to the reusable behavior of UITableViewCell you lost the reference of the invisible cell with all the child reference.

So you can store the text-field value by the textViewDidChange action in RelatieToevoegenCell class.

Salman Ghumsani
  • 3,647
  • 2
  • 21
  • 34