DBoyer
DBoyer

Reputation: 3122

Adding row to end of tableview with animation dynamically

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];

Upvotes: 1

Views: 1188

Answers (2)

Cameron Askew
Cameron Askew

Reputation: 1413

Try..

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

Upvotes: 2

bsarr007
bsarr007

Reputation: 1964

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.

Upvotes: 0

Related Questions