滚动后collectionview项不会在中心

时间:2021-02-24 07:58:39

标签: swift uicollectionview

我现在正在为图片制作一个 collectionView,我想让它像下面这样。

然而,当我向右/向左滚动时,下一个项目永远不会在中心,我尝试了很多方法仍然无法解决问题。 有人可以帮我吗?

enter image description here enter image description here

下面是代码。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        let cellCount = CGFloat(Config.banners.count)

        if cellCount > 0 {
            let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
            let cellWidth = screenSize.width - flowLayout.minimumInteritemSpacing
            flowLayout.itemSize = CGSize(width: cellWidth, height: 250)
            flowLayout.minimumLineSpacing = -60
            let totalCellWidth = cellWidth*cellCount
            let totalSpacingWidth = 30 * (cellCount - 1) 
            let contentWidth = collectionView.frame.size.width
            
            if (totalCellWidth < contentWidth) {
                print("totalCellWidth < contentWidth")
                let padding = (contentWidth - totalCellWidth) / 2.0
                return UIEdgeInsets(top: 0, left: padding, bottom: 0, right: padding)
            } else {
                print("totalCellWidth > contentWidth")
                return UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)
            }
        }
        return UIEdgeInsets.zero
    }

1 个答案:

答案 0 :(得分:0)

在您的代码中添加这些行 collectionviewflowdelegate 方法。它会起作用。我通过添加这些方法实现了同样的目的。

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let width  = UIScreen.main.bounds.width / 3.0
    let height = collectionView.frame.size.height
    return CGSize(width: width, height: height)
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
    return 0.0
}
相关问题