Search code examples
swiftuitableviewreloaddata

How can I empty my cell data inside a table view by pressing a button outside the table view?


I have a table view in my app with 4 different types of cells in it. I would like to be able to press a button in the nav bar (a clear button) and be able to empty the data in my cells. Some of my cells have segmented controls in them and I would like to be able to set them to zero after this button is tapped. How can I accomplish this, even for cells that are not in view but still need to be emptied?


Solution

  • Stop thinking about your cells and think about your data model. When the user presses the button, you reset the data. You then reload the table view, and your changes are picked up by the visible cells and all future cells, because you have cleverly written your cellForRowAt to make the cell reflect the data.

    Basically, what I've just said is more or less the golden rule of table views. You never operate directly on a cell; you operate on the data and reload the table, so that any cell that needs the data can retrieve it on demand.