How to insert new cell into UITableView in Swift

code Horizons picture code Horizons · Aug 7, 2015 · Viewed 133.1k times · Source

I'm working on a project where I have two UITableViews and two UITextFields, when the user presses the button the data in the first textField should go into the tableView and the second go into the second tableView. My problem is that I don't know how to put data in the tableView each time the user pushes the button, I know how to insert data with tableView:cellForRowAtIndexPath: but that works for one time as far as I know. So what method can I use to update the tableView each time the user hits the button?

Answer

EI Captain v2.0 picture EI Captain v2.0 · Aug 7, 2015

Use beginUpdates and endUpdates to insert new cell when button clicked.

First of all append data in your tableview array

Yourarray.append([labeltext])  

Then upate your table and insert new row

// Update Table Data
tblname.beginUpdates()
tblname.insertRowsAtIndexPaths([
NSIndexPath(forRow: Yourarray.count-1, inSection: 0)], withRowAnimation: .Automatic)
tblname.endUpdates()

This inserts cell and doesn't need to reload whole table but if you get any problem with this, you can also use tableview.reloadData()


Swift 3.0

tableView.beginUpdates()
tableView.insertRows(at: [IndexPath(row: yourArray.count-1, section: 0)], with: .automatic)
tableView.endUpdates()

Objective-C

[self.tblname beginUpdates];
NSArray *arr = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:Yourarray.count-1 inSection:0]];
[self.tblname insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tblname endUpdates];