Logan Logan - 3 months ago 59
iOS Question

UICollectionView scrollToItemAtIndexPath not functioning properly in navigation controller

I have a method that I use to scroll to the bottom of my collectionView

- (void) scrollToBottom {
if (_messagesArray.count > 0) {
static NSInteger section = 0;
NSInteger item = [self collectionView:_myCollectionView numberOfItemsInSection:section] - 1;
if (item < 0) item = 0;
NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
[_myCollectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
}
}


And it works perfectly! I have never had a problem at any point, it works 100% consistent . . . with a modal view presentation. If however, I push the viewController onto a navigation controller, it doesn't work. Rather, it only works if there's over 15 cells. Once I reach at least 15 cells, it again begins behaving perfectly. Prior to 15 cells, it either doesn't scroll at all, or scrolls a little bit.

I realize this is a long shot, but I'm scratching my head on this one and I thought maybe somebody might know what the heck is happening.

Troubleshoots:

Have you logged to make sure it's running? YES

Have you logged index path to make sure its trying to scroll to the correct index path? YES

EXAMPLE



enter image description here

WORKING MODAL EXAMPLE



enter image description here

Answer

I found the problem.

The NavigationController was automatically adjusting my top content inset for some reason. I was able to prevent this behavior by adding this:

- (void) scrollToBottom {

    if (_isNavigationControllerVersion) {
        _myCollectionView.contentInset = UIEdgeInsetsZero;
    }

    if (_messagesArray.count > 0) {
        static NSInteger section = 0;
        NSInteger item = [self collectionView:_myCollectionView numberOfItemsInSection:section] - 1;
        if (item < 0) item = 0;
        NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
        [_myCollectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:YES];
    }
}
Comments