1
votes

I have a tableView that begins completely empty, and as a user enters data and presses a "save" button a new cell needs to be added to the tableview. I have this working totally fine by adding the new data to my data array and calling [tableView reloadData], but I would like to use an animation for when the new cell is added. Im assuming I will need to use some of the tableView editing methods.

A cell needs to be added WITH animation every time "save" is pressed always to the bottom of the table view (always after the last row). I'm running into problems because my table is initially empty so I have no indexPath to the last row.

This is my attempt:

NSInteger lastSectionIndex = [self.tableView numberOfSections] - 1;
NSInteger lastRowIndex = [self.tableView numberOfRowsInSection:lastSectionIndex] - 1;
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];

[self.tableView beginUpdates];
[self.tableView insertRowsAtIndexPaths:@[pathToLastRow] withRowAnimation:UITableViewRowAnimationBottom];
[self.tableView reloadData];
[self.tableView endUpdates];
2
Is it only not working for the case where the table is empty?Cameron Askew
Yea.. but its also not working when I add a new cell it takes the data from the previous cell and adds that to the table, so I am always one cell behind.. I hope that makes senseDBoyer
I think it's an indexing issue, modified my answer a couple times but try the current code that's in right now.Cameron Askew

2 Answers

2
votes

Try..

NSInteger lastSectionIndex = MAX(0, [self.tableView numberOfSections] - 1);
NSInteger lastRowIndex = [self.tableView numberOfRowsInSection:lastSectionIndex];
NSIndexPath *pathToLastRow = [NSIndexPath indexPathForRow:lastRowIndex inSection:lastSectionIndex];
0
votes

You insertion index should be numbersOfRows without the -1 Remove the [self.tableView reloadData] line and you should also be sure your numbersOfRows method return a numbersOfRow + 1 at the end of your method.