Author: Justin Fletcher
Category : Objective-C , XCode
[tldr: code at bottom]
Let me explain the title. I wanted to have a UITableView that adds new rows, and also scrolls to the new row that just got inserted.
But theres the annoying that if you’re viewing older rows in the middle of the tableview, you don’t want the tableview to scroll you away from that when it adds a new row.
I created this method that only scrolls to the newly added row, when you’re at the end of the tableview, so if you’re viewing some data in the middle of the tableview, it won’t scroll you away from it. This works with both single-section and multi-section tableviews as well. Explanation in the code comments. It’s pretty simple actually.
It’s also useful for anyone looking for how to make the table scroll when adding a new row, regardless of where you are in the tableview.
Enjoy, this is coming straight from a new game project I’m working on.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
-(void)addRowAndScrollWithIndexPath:(NSIndexPath*)path { //check if the last viewable index path is one less than the path being //added. this way we know we're at the bottom. //array of visible paths. NSArray *visiblePaths = [table indexPathsForVisibleRows]; //last visible object's index path. NSIndexPath *bottomPath = [visiblePaths lastObject]; //row and section of last visible row. NSInteger bRow = [bottomPath row]; NSInteger bSection = [bottomPath section]; //row and section or row in parameter. NSInteger row = [path row]; NSInteger section = [path section]; /* so it should only scroll if you're viewing the index path previous to the path specified in the parameter. (only possible if their sections are equal AND the parameter row is one more than the last visible row), OR (the section of the parameter is one more than the last visible row AND the row of the parameter is 0), meaning its the first in a new section. */ //first condition. BOOL nextRowInSameSection = (section == bSection) && (row == (bRow+1)); //second condition. BOOL firstRowInNextSection = ((section == (bSection+1)) && (row == 0)); //one or the other. BOOL shouldScroll = nextRowInSameSection || firstRowInNextSection; //array of indexPaths to add. NSArray *indexPaths = [NSArray arrayWithObject:path]; //add the row to the table view. [table insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade]; //if you should scroll based on the booleans above.. do so to the new path. if (shouldScroll) { [table scrollToRowAtIndexPath:path atScrollPosition:UITableViewScrollPositionBottom animated:YES]; } } |
As always, comments and questions are welcome.