scrollToItemAtIndexPath: atScrollPosition: animated:

时间:2023-03-09 17:55:14
scrollToItemAtIndexPath: atScrollPosition: animated:

oh my god

今天死在scrollToItemAtIndexPath: atScrollPosition: animated:方法上面,scrollPosition这个参数控制cell具体停留在上下左右中到底哪个位置,看了API有7个枚举值

UICollectionViewScrollPositionNone                 = ,

// The vertical positions are mutually exclusive to each other, but are bitwise or-able with the horizontal scroll positions.
// Combining positions from the same grouping (horizontal or vertical) will result in an NSInvalidArgumentException.
UICollectionViewScrollPositionTop = << ,
UICollectionViewScrollPositionCenteredVertically = << ,
UICollectionViewScrollPositionBottom = << , // Likewise, the horizontal positions are mutually exclusive to each other.
UICollectionViewScrollPositionLeft = << ,
UICollectionViewScrollPositionCenteredHorizontally = << ,
UICollectionViewScrollPositionRight = <<

之前没有去理解过它几个参数的意思,要实现在二级界面通过indexPath获取到一级界面的collectionView的对应位置的cell

UIView *sourceCell = [_sourceView cellForItemAtIndexPath:indexPath];
if (!sourceCell) {
[_sourceView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
[_sourceView layoutIfNeeded];
sourceCell = [_sourceView cellForItemAtIndexPath:indexPath];
}

此时cell存在nil的情况,collectionView.visibleCells没有这个cell,需要从重用池获取,所以要滚动到这个cell位置后走layoutSubViews布局,这样才拿的到cell

在给参数时给了 UICollectionViewScrollPositionLeft  ,然后pop回去就一直没效果,用了代理 block都还是不行,以为是layoutIfNeeded的问题搞了很久。

最后 给 UICollectionViewScrollPositionCenteredVertically 这个就成了。

根据API的解释 分成水平滚动和垂直滚动

可以想象的是当collectionView水平滚动时cell的定点相对于整个collectionView的左中右位置

当垂直滚动时cell的定点相对于整个collectionView的上中下位置