UICollectionView:ScrollToItem 到中心单元格在水平集合视图上不起作用

Pas*_*cal 5 uikit ios uicollectionview swift

我有一个带有内容偏移的水平 UICollectionView,以便每个元素(包括最左边的项目)都可以滚动到中心:

let cvOffset = (UIScreen.main.bounds.width - tileSize) / 2
collectionView.contentInset = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)
collectionView.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)
Run Code Online (Sandbox Code Playgroud)

但是,当我使用scrollToItem方法时,它只适用于右半部分的项目。如果我选择左半部分的任何项目,则会输入第一个单元格。你知道为什么吗?

collectionView.scrollToItem(at: IndexPath.init(row: sender.tag, section: 0), at: .centeredHorizontally, animated: true)
Run Code Online (Sandbox Code Playgroud)

Lad*_*lav 4

不确定这是否是UICollectionView流程布局中的错误或某种期望的结果,但您可以通过将UICollectionViewFlowLayouts设置sectionInset为内容插入来完成您需要的操作,然后scrollToItem将按预期工作:

因此,删除您的内容contentInset并将以下内容添加到您的布局中:

layout.sectionInset = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)
Run Code Online (Sandbox Code Playgroud)

在我的测试应用程序中,它做了它应该做的事情,因此滚动到选定的单元格并居中为所有indexPaths