iosswiftuicollectionviewuicollectionviewdelegateflowlayout

Space between collection view cells is always 0


I am trying to have a space between my cells, but for some reason it is always 0. What am I doing wrong?

import UIKit

class AlbumPlayerProgressBar: UICollectionView {

    ...

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.register(UINib(nibName: "ProgressBarCell", bundle: nil), forCellWithReuseIdentifier: NSStringFromClass(ProgressBarCell.self))
        self.dataSource = self
        self.delegate = self
    }
}

extension AlbumPlayerProgressBar: UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return numOfSlides
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(ProgressBarCell.self), for: indexPath) as! ProgressBarCell

        ...
        return cell
    }
}

extension AlbumPlayerProgressBar: UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAt: IndexPath) -> CGSize
    {       
        return CGSize(width: segmentWidth, height: segmentHeight)
    }

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

Solution

  • You can use minimumInteritemSpacingForSectionAt and minimumLineSpacingForSectionAt , and set the return value to what space you want:

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