0

I am now making a collectionView for pics and I wanna make it like below.

However, when I scroll to the right/left, the next item will never in the center and I tried so many methods already still cannot solve the problem. Can anyone help me?

enter image description here enter image description here

Below is the code.

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
    }
Berlin
  • 65
  • 1
  • 8
  • You'll need to override `targetContentOffset(forProposedContentOffset:withScrollingVelocity:)`, check for more details [here](https://stackoverflow.com/questions/33855945/snap-to-center-of-a-cell-when-scrolling-uicollectionview-horizontally/43637969#43637969) – ScorpiCon Feb 24 '21 at 09:30

1 Answers1

0

add these lines collectionviewflowdelegate method in your code. It will work. I achieved the same thing by adding these methods.

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
}