UICollectionViewScrollPosition不起作用

Pip*_*ppo 1 ios uicollectionview swift

我有一个collectionview,我试图以编程方式滚动.问题是,如果要滚动到的单元格在集合视图中可见,则不会将其滚动到中心.所以对于下面的图像,下面的单元格是项目1.它不会滚动到它,但它将滚动到项目1到项目2.

我一直在尝试使用UICollectionVieScrollPosition.CenterVertically,但这似乎不起作用.

self.collectionView?.scrollToItem(at: IndexPath(row: 1, section: 0), at: UICollectionViewScrollPosition.centeredVertically, animated: true)
Run Code Online (Sandbox Code Playgroud)

有没有办法绕过这个强制滚动对集合中心可见的单元格?

在此输入图像描述

Pip*_*ppo 9

我发现这样做的最好方法是不使用scrollToItem,而是获取索引的CGRect,然后使其可见.

     let rect = self.collectionView.layoutAttributesForItem(at: IndexPath(row: 5, section: 0))?.frame
     self.collectionView.scrollRectToVisible(rect!, animated: false)
Run Code Online (Sandbox Code Playgroud)

  • 投票。对我来说 ```scrollToItem``` 不会滚动到我想要的位置,并且还有一些布局问题(有时会用疯狂的单元格重新排列使 collectionview 重新布局)。这种方法非常可靠。但有人知道为什么吗? (2认同)

boo*_*oog 5

我试图用 0.1 秒延迟它。就我而言,现在看起来不错:

collectionView.collectionViewLayout.invalidateLayout() //just in case, iOS10 may crash btw.

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    self.collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

更新:

好的,事实证明我正在使用layout.estimatedItemSizeautolayout计算我的单元格的宽度,这就是我遇到这个问题的原因。也就是说,对我来说,这是因为CollectionView's dynamic sizing. 在我返回手动计算宽度后,一切正常。(通过使用-collectionView:layout:sizeForItemAt:


Fay*_*007 0

首先,您需要找到CollectionView的中心,具体方法如下:

private func findCenterIndex() -> Int {
        let center = self.view.convert(numberCollectionView.center, to: self.numberCollectionView)
        let row = numberCollectionView!.indexPathForItem(at: center)?.row


        guard let index = row else {

            return 0
        }


        return index
    }
Run Code Online (Sandbox Code Playgroud)

然后获取您下面的行号scrollToItem,它应该可以工作:

collectionView.scrollToItem(at: IndexPath(item: findCenterIndex(), section: 0), at: .centeredVertically, animated: false)
Run Code Online (Sandbox Code Playgroud)

调用它从viewDidLayoutSubviews()