Adam Adam - 3 years ago 140
Swift Question

Swift What is the best way to replace content in TableViewCell

I want to do something like in the GIF
I tried 2 ways, one was hiding the elements on selecting the row and showing others, but that's not really elegant and doesn't work very well
and second was creating 2 views, one with labels, another with buttons, adding them as subviews to cell.contentView but that caused some issues with other cells as they were displaying wrong data. How can I recreate something like this?

enter image description here

Answer Source

I think something like this would work:

  1. Use 2 different UITableViewCells: add them to the table view in your storyboard and design them separately, also you can use 2 different UITableViewCell subclasses for them

  2. Have an array in the tableview's datasource class that will define the type of the cell from each row (e.g. the simplest solution would be an array of integers, with values: 0 representing the first cell, 1 representing the second cell)

  3. Initialise that array with 0s for each row

  4. In tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell :

    • if cellTypes[indexPath.row] == 0 --> return a cell of first type
    • if cellTypes[indexPath.row] == 1 --> return a cell of the second type
  5. In tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) :

    • switch the cell type in the array
    • reload the row with animation, e.g. you can use .fade or .left or .right etc.

tableView.reloadRows(at: [indexPath], with: .fade)

EDIT: Your solution is also a good one, but it can cause problems when the cells are dequeued, so if a cell with the wrong subviews is dequeued then you need to switch the subviews back in the cellForRowAt indexPath datasource method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download