0
votes

I am playing with a table as below (I've seen multiple threads on this topic but couldn't answer my question):

func numberOfSections(in _: UITableView) -> Int {
        3
    }

func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
    if section == 0 {
        return 3
    } else if section == 1 {
        return 4
    } else {
        return 2
    }
}

Then after clicking on a cell I want a new cell inserted into the same section at row index 0. I wrote the below:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     tableView.insertRows(at: [IndexPath(row: 0, section: indexPath.section)], with: .left)
   }

I get this error: Exception NSException * "Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (3) must be equal to the number of rows contained in that section before the update (3), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out)."

I assume I should somehow update the data source, but since in my case I return const values for rows in sections is there a way to update the the number of rows in section? (the numberOfRows in section only returns immutable value). Thank you

1
You can't simultaneously have a fixed and variable number of rows in a section; If you want to be able to add rows you need to return the correct row count in numberOfRows() - Paulw11

1 Answers

1
votes

in my case I return const values

There you go! If you are going to modify the number of rows you need variables

For example

var sections = [3,4,2]

func numberOfSections(in _: UITableView) -> Int {
    return sections.count
}

func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
    return sections[section]
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    sections[indexPath.section] += 1
    tableView.insertRows(at: [IndexPath(row: 0, section: indexPath.section)], with: .left)
}