dgelinas21
dgelinas21

Reputation: 641

TableView Update Error while inserting new cell

I have a UITableView that is populated from all one xib file. I am trying to insert another cell below a cell upon clicking a cell (which would be populated by a separate xib). The idea of this would be to make a sort of drop down menu.

I am using the code below currently for the function to run when selecting a cell:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        //below prints the name of the selected user
        print(name[indexPath.row])

        var contactNum = ""

        //below inserts a new cell into the table view, below the selected cell
        // Update Table Data
        myTableView.beginUpdates()
        myTableView.insertRowsAtIndexPaths([
            NSIndexPath(forRow: (indexPath.row)+1, inSection: 0)
            ], withRowAnimation: .Automatic)
        let cell = myTableView.dequeueReusableCellWithIdentifier("DDOCell")
        myTableView.endUpdates()

        //below reloads the table view after changes are made
        myTableView.reloadData()

    }

but continue to get the following error

'Invalid update: invalid number of rows in section 0.  The number of rows contained in an existing section after the update (4) must be equal to the number of rows contained in that section before the update (4), 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).'

Doe anyone know the issue with why a new cell with different datasource is not being created below the selected?

Upvotes: 0

Views: 59

Answers (1)

rmaddy
rmaddy

Reputation: 318774

You get the error because you do not first update your data model before calling insertRowsAtIndexPath. Given your print statement you probably need something like (in Swift 3):

name.insert("some new name", at: indexPath.row + 1)

Please note that the calls to beginUpdates and endUpdates are not needed here since you are only making one call to delete|insert|reloadRowsAtIndexPaths.

Also note that you must never call dequeueReusableCellWithIdentifier outside of cellForRowAt. If you really need a cell from a table in any other method, such as didSelectRowAt, use cellForRow(at:).

Upvotes: 2

Related Questions