anton68
anton68

Reputation: 407

How can the content of a UITableViewCell be updated properly?

I have a TableView whose cells content need to be updated when it's TableViewRowAction is excecuted. More precisely I want to update a UILabel inside the cell. Setting a new text to this label inside the action is no problem but when scrolling down/up and the cell gets reloaded, then this label inside the cell has the same text as before changing it.

I know that the cells get reused and that's why I want to know how to "avoid" this effect and how to update the content of the cells properly. I have already tried to call TableView.ReloadData() which seems to solve the problem but the cells appear in a completly different order which doesn't look very nice.

Upvotes: 3

Views: 606

Answers (3)

Sanket Ray
Sanket Ray

Reputation: 1141

To achieve this you must create an Array that acts as a dataSource for your labels. When you are changing the text for a specific label, you must update the array. You can get the exact update location from the property indexPath of the method cellForRowAt. Every single time you scroll up and down, cellForRowAt method is called. Just use something like

label.text = array[indexPath.row]

Upvotes: 0

Shehata Gamal
Shehata Gamal

Reputation: 100503

As you said table cells are reused , this means you have to keep a model array for the whole table and make all the changes to it , then reload the table more importantly to set the content of the cell index in cellForRowAt

Upvotes: 1

MQLN
MQLN

Reputation: 2328

The most straightforward approach is to update the data that your UITableView is drawing from (i.e. the array of data that you're populating each cell from has been updated to reflect your text change), then reload the specific cell of the UITableView:

let indexPath = IndexPath(row: 0, section: 0)
tableView.reloadRows(at: [indexPath], with: .automatic)

Upvotes: 1

Related Questions