Frilau
Frilau

Reputation: 59

Increase size of spacing between cells in collection view

I want different spacing between my cells inside my collectionview.

My collectionview contains only one section. I know it's possible to change the spacing between sections but I'll like between cells.

I would like the spacing to be greater between the centered cell and its sides, and that the spacing of the other cells do not move. Basically, my white circle does not touch the edges of neighboring cells without changing all the spacing.

Image of my problem here :

Image of my problem here

There is a solution ?

Upvotes: 1

Views: 978

Answers (2)

PGDev
PGDev

Reputation: 24341

You can try creating 3 different sections.

  1. 1st Section - section containing cells before the larger cell, with inter item spacing as 10
  2. 2nd Section - section containing the larger cell, with section insets as (top: 0, left: 20, bottom: 0, right: 20)
  3. 3rd section - section containing cells after the larger cell, with inter item spacing as 10

You can change the values as per your requirements.

Here is what the code says:

func numberOfSections(in collectionView: UICollectionView) -> Int
{
    return 3
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    if section == 1
    {
        return 1
    }
    return 2
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    if indexPath.section == 1
    {
        cell.backgroundColor = UIColor.red
    }
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
{
    if indexPath.section == 1
    {
        return CGSize(width: 100, height: 100)
    }
    return CGSize(width: 82, height: 82)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
{
    if section == 1
    {
        return 0
    }
    return 5
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
{
    if section == 1
    {
        return UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
    }
    return .zero
}

Screenshot:

enter image description here

Let me know if you still face any issues.

Upvotes: 1

Andrew Kochulab
Andrew Kochulab

Reputation: 325

You could implement this method in your view controller: collectionView:layout:minimumInteritemSpacingForSectionAtIndex

Upvotes: 1

Related Questions