iOS-UICollectionView-reloadData之后滚动到指定位置

503 阅读1分钟

有个页面用UIColletionView写的,现在需求有变更:要求要刷新数据之后要滚动到指定位置,界面如 图 1.1

图 1.1 该页面宽度固定最多展示5个可视cell,刷新之后滚动到指定位置,如果敲了以下代码:

[_collectionView reloadData];
[_collectionView scrollToItemAtIndexPath:_currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

然后就你就会发现执行完reloadData方法之后就马上执行scrollToItemAtIndexPath: atScrollPosition: animated:方法了,然后才执行刷新cell的方法

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

所以根本不会滚动到指定位置,然后我猜reloadData它应该是采用分线程来刷新数据的,然后我就用在主线程来让它滚动,果然可以实现.

[_collectionView reloadData];
dispatch_async(dispatch_get_main_queue(), ^{
         [_collectionView scrollToItemAtIndexPath:_currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    });

然后发现有还有一个自带的方法也是可以实现的:

[_collectionView performBatchUpdates:^{
        //这里有个坑:更新前我们需要判断将要刷新的数据相对于之前是增加了还是减少了,或者没有变化,不然会闪退
    } completion:^(BOOL finished) {
        [_collectionView scrollToItemAtIndexPath:_currentIndexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    }];