UICollectionView 设置ContentInset 导致scrollToItemAtIndexPath不正确的bug

设置了ContentInset

我在项目中使用了HJCarouselViewLayout布局.同时为了保证点击cell都可以达到 居中 效果.设置了collectionViewContentInset

_viewHeight = CGRectGetWidth(self.collectionView.frame);
        _itemHeight = self.itemSize.width;
        self.collectionView.contentInset = UIEdgeInsetsMake(0, (_viewHeight - _itemHeight) / 2, 0, (_viewHeight - _itemHeight) / 2);

使用系统提供的 scrollToItemAtIndexPath:indexPath atScrollPosition:

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.colletionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
}
bug截图
!!!!bug出现

点击第5个cell的时候,UICollectionView就会直接滑动到最左侧,导致中间的cell无法点击居中.
1.怀疑是scrollToItemAtIndexPath:indexPath atScrollPosition:是bug的根源,是苹果底层的问题.
2.更换功能实现的方法使用setContentOffset: animated:

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
        CGFloat collectionViewWidth = CGRectGetWidth(collectionView.frame);
        UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
        CGPoint offset = CGPointMake(cell.center.x - collectionViewWidth / 2, 0);
        [collectionView setContentOffset:offset animated:YES];
   

    
}

运行 -------
binggo!!!!
bug解决!!!!


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

推荐阅读更多精彩内容