首页 > 解决方案 > 使用部分可见的上一个和下一个项目滚动时将集合视图居中

问题描述

我想达到这个图像中的结果,这就是我启动集合视图(第一项)时得到的结果: 在此处输入图像描述

但是,当我左右滚动插图时,似乎不再尊重并且该项目不再像这样居中:

在此处输入图像描述

我的部分代码:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

return  CGSize(width: view.bounds.size.width - 60 , height: 450)

}

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 30, bottom: 0, right: 30)

}

标签: iosswiftcollectionviewinsets

解决方案


嗨,我确实了解您要求只要将集合视图滚动一点,您就必须完全显示下一个单元格。

为了在collectionView中实现这一点,将显示单元格

func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !(indexPath.section == 0), !(indexPath.row == 0) {
    let indexPath = IndexPath(item: indexPath.row + 1, section: indexPath.section)
        self.collectionView.scrollToItem(at: indexPath, at: .centeredVertically, animated: true)
 }
}

滚动到下一个项目。

希望这对你有用:)


推荐阅读