I have a UITableView that I am adding a row to with an animation (using insertRowsAtIndexPaths:withRowAnimation:
). This is all good as long as the table is not longer than the screen.
If it is bigger than the screen then I am trying to scroll to the bottom, but it is not quite working how I want. If I scroll to the new row after it is added I miss the animation. If I try to scroll to that indexPath before it is added it throws an exception (about it not being a valid indexPath)
Is there a solution to this other than adding a blank row?
I had this same issue. Here was my solution.
First - Update your data source
Second -
NSIndexPath *path = [NSIndexPath indexPathForRow:([arrayWhichFeeds count] - 1 inSection:0]];
NSArray *paths = [NSArray arrayWithObject:path];
[myTableView insertRowsAtIndexPaths:paths withRowAnimation:UITableViewRowAnimationTop];
[myTableView scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES];
*Please note that this IS NOT wrapped in the [tableView beginUpdades]
and [tableView endUpdates]
code. If you do it will not work as desired.
Give it a try, it should animate in the new rows from the bottom while scrolling to them.
Yes there is a solution without adding a blank row.
Note: In the code, I consider that there is only 1 section but many rows. You can modify the code to manage multiple sections as well.
- (void)theMethodInWhichYouInsertARowInTheTableView
{
//Add the object in the array which feeds the tableview
NSString *newStringObject = @"New Object";
[arrayWhichFeeds addObject:newStringObject];
[myTableView beginUpdates];
NSArray *paths = [NSArray arrayWithObject:[NSIndexPath indexPathForRow:([arrayWhichFeeds count] - 1) inSection:0]];
[myTableView insertRowsAtIndexPaths:paths withRowAnimation:NO];
[myTableView endUpdates];
[myTableView reloadData];
[myTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:([arrayWhichFeeds count] - 1) inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
Other techniques, including those mentioned under this question did not work for me. This did however:
I worked this technique out (and wrote this answer) when I 1st started iOS development, but this did work out long term.
Remeber to do this in the main thread otherwise it won't scroll to the required position.
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