iOS collectionView定位/偏移到指定位置 performBatchUpdates

手动定位
  • 直接定位到某一个item,没什么问题
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
[collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:true];
  • collectionView有sectionHeader或者sectionFooter
UICollectionViewLayoutAttributes * attrs = [_collectionView layoutAttributesForItemAtIndexPath: indexPath];

[collectionView setContentOffset:CGPointMake(0, attrs.frame.origin.y)];
或者:
[collectionView scrollRectToVisible:attrs.frame animated:true];
自动偏移

需求是网络请求完了之后进行自动定位到某一个位置
直接定位到某一个item,可直接在reloadData之后直接操作

[collectionView reloadData];
[collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionTop animated:true];

but:当需要定制到某个section,比如要定位到第二个section的header
reloadData 之后再取layoutattributes是取不到的 所以解决方案为:

    [collectionView reloadData];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    [collectionView performBatchUpdates:^{
        [collectionView reloadItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        UICollectionViewLayoutAttributes * attrs = [_collectionView layoutAttributesForItemAtIndexPath: indexPath];
        [collectionView setContentOffset:CGPointMake(0, attrs.frame.origin.y)];
    }];

ps:对于 indexPath 注意不要搞出越界的问题

关于performBatchUpdates 注视是这么说的:

allows multiple insert/delete/reload/move calls to be animated simultaneously. Nestable.

so: collectionView关于cell的增删操作尽量都放到这个block里面来操作,保证别出现什么crash~ 水一波~

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容