0

I have a UICollectionView with a custom UICollectionViewLayout that places items vertically on the screen. Now as I'm adding a new item to some place in the view, I'd like to scroll to the new item at the same time. Here's my code:

CardsCollection.InsertItems(new NSIndexPath[] { nextIndex });
CardsCollection.ScrollRectToVisible(this.layout.TargetViewFrameForItem(nextIndex), true);

(I'm using Xamarin, but OC guys you get the idea..)

This works most of the time, but not for adding items to the very end of the view. In that case, the screen only scrolls up a little bit, not showing the entirety of the new item. It seems that the view's content size wasn't immediately expanded after InsertItems was called, although UICollectionViewLayout.CollectionViewContentSize was actually called and returned the correct size parameters.

I tried the following method which worked functionally:

CardsCollection.PerformBatchUpdates(
    () => CardsCollection.InsertItems(new NSIndexPath[] { nextIndex }), 
    (finished) => CardsCollection.ScrollRectToVisible(this.layout.TargetViewFrameForItem(nextIndex), true));

However, the scrolling only started after the animation for adding the new item was completed. I'm not very comfortable with this aesthetically and would still like to have both actions take place at the same time. Is there any easy way to do so?

Todd Li
  • 3,209
  • 21
  • 19

1 Answers1

0

Related to this answer - Animated scroll-to-item in UICollectionView doesn't always work - if the number of items are changing, you need first of all reload the collectin view and just then use ScrollRectToVisible

Community
  • 1
  • 1
choper
  • 1,292
  • 8
  • 10
  • Thank you for the link. I tried to call `ReloadData()` before `ScrollRectToVisible`, but it still only scrolled a little bit. Guess it's indeed tricky to expand the view immediately. – Todd Li Mar 18 '14 at 17:48
  • so try scroll to item by index path: `CardsCollection.ScrollToItem(nextIndex, UICollectionViewScrollPosition.CenteredHorizontally, true)` – choper Mar 18 '14 at 17:53