iosswiftuitableviewexpandable

(Swift) How to manage names of tableView cells after expanding tableViewSection?


In one of sections, when I click toggleSwitch it should expand with number of the same cells depending on array.count

Method below works fine. When I click toggle it expands a section with number of rows equal number of elements in array:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        switch section {
        case 0:
            return 7
        case 4:
            if expand == true {
                return array.count + 1
            }
            else {
                return 1
            }
        default:
            return 1
        }
    }

array can have any number of elements, depending on data in Realm. So it can be 0, but it can also be 5, 14 etc.
Code in CellForRowAt also works fine, expands the section with animation:

 cell.labelCell.text = "elements (\(array.count))"

 cell.cellSwitch.isOn = self.expand

 cell.callback = { [unowned self] check in
      self.expand = check
      UIView.transition(with: tableView,
                          duration: 0.5,
                          options: .transitionCrossDissolve,
                          animations: { self.tableView.reloadData()})
                }

NOTE : All new cells in section are the same type as their parent cell. So each of new cells has got its own name, switch...
Question : How can I make new cells have their names like the elements in array. Like: if the first element in array is "abc" , I want to make first cell's : cell.labelCell.text = "abc" (array[0])


Solution

  • Replace

    cell.labelCell.text = "elements (\(array.count))"
    

    with

    cell.labelCell.text = "elements (\(array[indexPath.row]))"
    

    Side note:

    You could get the animation for free if you reload only the section rather than the entire table view.