I'm working on a project where I have two UITableView
s and two UITextField
s, 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?
Use beginUpdates and endUpdates to insert a new cell when the button clicked. Nice that you have provided the Objective-C version as well.
Step 1: Easiest way to add a new row The easiest way to add a new row to a UITableView would be to add a new item to the data and then call the reloadData method on the `UITableview. This will add a new row to our UITableView because we have added mercury to our data and then we called reloadData .
For performance reasons, a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in its tableView(_:cellForRowAt:) method. A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.
Use beginUpdates
and endUpdates
to insert a new cell when the button clicked.
As @vadian said in comment,
begin/endUpdates
has no effect for a single insert/delete/move operation
First of all, append data in your tableview array
Yourarray.append([labeltext])
Then update your table and insert a 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 the 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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With