Kirill Kirill - 1 month ago 25
Swift Question

Add additional rows in TableView

I use Swift 3.
I have UITableView with 7 rows:

override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
if (IndexPath.row == 6)
{
tableView.beginUpdates()
var index = IndexPath(row: 7, section: 0)
tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)
tableView.endUpdates()
}
}


I want to add additional cell when I'm scrolling to last cell in table.
But I got this error:


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

Answer

You should update your datasource when you insert or delete any rows from tableView, sot that the number of objects is kept equal to the number of rows in tableView

func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int {        
    return dataSource.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if (IndexPath.row == 6) {
        tableView.beginUpdates()
        var index = IndexPath(row: 7, section: 0)
        let newObject = // create new model object here
        dataSource.insert(newObject, at: 7)
        tableView.insertRows(at: [index], with: UITableViewRowAnimation.automatic)                    
        tableView.endUpdates()
    }
}