首页 > 解决方案 > UICollectionView:ScrollToItem 到中心单元格在水平集合视图上不起作用

问题描述

我有一个带有内容偏移量的水平 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)

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

collectionView.scrollToItem(at: IndexPath.init(row: sender.tag, section: 0), at: .centeredHorizontally, animated: true)

标签: iosswiftuicollectionviewuikit

解决方案


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

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

layout.sectionInset = UIEdgeInsets(top: 0, left: cvOffset, bottom: 0, right: cvOffset)

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


推荐阅读