I've just run in to a similar / the same issue after adding an item to a UICollectionView
.
What's happening
The issue seems to be that immediately following [collectionView reloadData]
or [collectionView insertItemsAtIndexPaths: @[newItemIndexPath]]
, the collection view's content size is not yet updated.
If you then try to scroll the added item visible, it will fail because the content rect doesn't yet include space for the new item.
A fix
There is a simple and fairly robust work around, which is to post the scroll event on to the next iteration of the run loop like this:
const NSUInteger newIndex =
[self collectionView: self.collectionView numberOfItemsInSection: 0] - 1;
NSIndexPath *const newPath =
[NSIndexPath indexPathForItem: newIndex
inSection: 0];
[self.collectionView insertItemsAtIndexPaths: @[newPath]];
UICollectionViewLayoutAttributes *const layoutAttributes =
[self.collectionView layoutAttributesForItemAtIndexPath: newPath];
dispatch_async(dispatch_get_main_queue(), ^{
[self.collectionView scrollRectToVisible: layoutAttributes.frame
animated: YES];
});
Isn't there a nicer fix?
While it works, this "post the scroll call on the next run loop tick" shenanigans feels hacky.
It would be preferable if UICollectionView
could invoke a callback when it finished updating the content rect. UIKit has callbacks of this style for other methods that perform asynchronous updates to its model. For example, a completion block for UIViewController
transitions and UIView
animations.
UICollectionView
does not provide this callback. As far as I know, there is no other simple clean way to find when it completes its update. In the absence of this, the next run loop tick is a viable horse proxy for the callback unicorn we would prefer to use.
Anything else to know?
It's probably useful to know that UITableView
also has this issue. A similar workaround should work there too.