UICollectionView 设置ContentInset

2018-04-24  本文已影响0人  蝼蚁撼树
设置了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
上一篇下一篇

猜你喜欢

热点阅读