Jordan H
Jordan H

Reputation: 55865

Insert rows at top of UITableView without modifying scroll position when using UITableViewAutomaticDimension

How can one insert rows into a UITableView at the very top without causing the rest of the cells to be pushed down - so the scroll position does not appear to change at all?

Just like Facebook and Twitter when new posts are delivered, they are inserted at the top but the scroll position remains fixed.

My question is similar to this this question. What makes my question unique from that question is that I'm not using a table with fixed row heights - I'm using UITableViewAutomaticDimension and an estimatedRowHeight. Therefore the answers suggested there will not work because I cannot determine the row height.

I have tried this solution that doesn't involve taking row height into consideration, but the contentSize is still not correct after reloading, because the contentOffset set isn't the same relative position - the cells are still pushed down past where they were before the insert. This is because the cell hasn't been rendered on screen so iOS doesn't bother to calculate the appropriate height for it until it's about to appear, therefore contentSize is not accurate.

CGSize beforeContentSize = tableView.contentSize;
[tableView reloadData];
CGSize afterContentSize = tableView.contentSize;
CGPoint afterContentOffset = tableView.contentOffset;
tableView.contentOffset = CGPointMake(afterContentOffset.x, afterContentOffset.y + afterContentSize.height - beforeContentSize.height);

Alain pointed out rectForCellAtIndexPath which forces iOS to calculate the appropriate height. I can now determine the proper height for the inserted cells, but the scroll view's contentSize is still not correct, as is evidenced when I iterate over all cells and add up the heights which is a larger than contentSize.height. So ultimately when I set the contentOffset manually it's not scrolling to the correct location.

Original code:

//update data source
[tableView beginUpdates];
[tableView insertRowsAtIndexPaths:newIndexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView endUpdates];

In this scenario, what can be done to achieve the desired behavior?

Upvotes: 14

Views: 8803

Answers (5)

Baran
Baran

Reputation: 2820

My working solution for iOS 13 & Swift 5:

Note: Only tested with dynamic cell heights (UITableViewAutomaticDimension / UITableView. automaticDimension).

P.S. None of the solutions posted here did work for me.

extension UITableView {
    /**
     Method to use whenever new items should be inserted at the top of the table view.
     The table view maintains its scroll position using this method.
     - warning: Make sure your data model contains the correct count of items before invoking this method.
     - parameter itemCount: The count of items that should be added at the top of the table view.
     - note: Works with `UITableViewAutomaticDimension`.
     - links: https://bluelemonbits.com/2018/08/26/inserting-cells-at-the-top-of-a-uitableview-with-no-scrolling/
     */
    func insertItemsAtTopWithFixedPosition(_ itemCount: Int) {
        layoutIfNeeded() // makes sure layout is set correctly.
        var initialContentOffSet = contentOffset.y

        // If offset is less than 0 due to refresh up gesture, assume 0.
        if initialContentOffSet < 0 {
            initialContentOffSet = 0
        }

        // Reload, scroll and set offset:
        reloadData()
        scrollToRow(
            at: IndexPath(row: itemCount, section: 0),
            at: .top,
            animated: false)
        contentOffset.y += initialContentOffSet
    }
}

Upvotes: 0

Azephiar
Azephiar

Reputation: 501

Late to the party but this works even when cell have dynamic heights (a.k.a. UITableViewAutomaticDimension), no need to iterate over cells to calculate their size, but works only when items are added at the very beginning of the tableView and there is no header, with a little bit of math it's probably possible to adapt this to every situation:

func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == 0 {
            self.getMoreMessages()
        }
}

private func getMoreMessages(){
        var initialOffset = self.tableView.contentOffset.y
        self.tableView.reloadData()
        //@numberOfCellsAdded: number of items added at top of the table 
        self.tableView.scrollToRowAtIndexPath(NSIndexPath(forRow: numberOfCellsAdded, inSection: 0), atScrollPosition: .Top, animated: false)
        self.tableView.contentOffset.y += initialOffset
}

Upvotes: 11

Owen
Owen

Reputation: 9

Meet the same problem and still do not find a elegant way to solve it.Here is my way,suppose I want to insert moreData.count cells above the current cell.

// insert the new data to self.data
for (NSInteger i = moreData.count-1; i >= 0; i--) {
    [self.data insertObject:moreData[i] atIndex:0];
}

//reload data or insert row at indexPaths
[self.tableView reloadData];

//after 0.1s invoke scrollToRowAtIndexPath:atScrollPosition:animated:
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:moreData.count inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
});

The advantage is fixed the position before and after inserting new data.The disadvantage is we can see the screen flash (the topmost cell shows and move up)

Upvotes: 0

Loaf Box
Loaf Box

Reputation: 11

Also, single row sections can accomplish desired effect

If a section already exists at the specified index location, it is moved down one index location. https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableView_Class/index.html#//apple_ref/occ/instm/UITableView/insertSections:withRowAnimation:

let idxSet = NSIndexSet(index: 0)
self.verseTable.insertSections(idxSet, withRowAnimation: .Fade)

Upvotes: 1

Alain T.
Alain T.

Reputation: 42139

I think your solution was almost there. You should have based the new Y offset on the "before" Y offset rather than the "after".

..., beforeContentOffset.y + afterContentSize.height - beforeContentSize.height

(you would need to save the beforeContentOffset point before the reload data though)

Upvotes: 0

Related Questions