>我无法使用 collectionView 的此功能滚动到项目
collectionView.selectItem(at: IndexPath(row: 10 , section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
此集合视图是水平的
您当前只是在 indexPath 中选择集合视图项,这不会滚动到项。您需要在所选项目的位置滚动。添加以下方法进行滚动:
collectionView.selectItem(at: IndexPath(row: 10 , section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
collectionView.scrollToItem(at: IndexPath(row: 10 , section: 0), at: .centeredHorizontally, animated: true)
谢谢大家。我用这段代码解决了。我的错误代码是self.categoryItemsCollection.selectItem(at: IndexPath(row: indexPath.section, section: 0), animated: true, scrollPosition: UICollectionViewScrollPosition.centeredHorizontally)
只是将 scrollPosition 参数更改为 .centeredHorizontally self.categoryItemsCollection.selectItem(at: IndexPath(row: indexPath.section, section: 0), animated: true, scrollPosition: .centeredHorizontally)