Set offset or initial position for a cell in a collection view

10,428

Solution 1

You could just set Section Insets for Collection View Flow Layout without code.

enter image description here

Solution 2

Swift 5 / Xcode 11

Thanks Alexander Spirichev.

Based on his answer, you can also set the left inset to 35 points programmatically:

let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.minimumLineSpacing = 8
layout.sectionInset = UIEdgeInsets(top: 0, left: 35, bottom: 0, right: 0)

collectionView.setCollectionViewLayout(layout, animated: false)

Solution 3

You need to set contentInset

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(top, left, bottom, right);
}

you can see in detail here

Share:
10,428
Jonathan Solorzano
Author by

Jonathan Solorzano

Updated on June 13, 2022

Comments

  • Jonathan Solorzano
    Jonathan Solorzano almost 2 years

    I want to add some space before the first cell in a collection view, something like an offset, my collection view has a horizontal scroll position.

    Here is my current collection view:

    current

    It has a leading constraint of 35, what I want is the cell to start at an "x" position of 35 but with the ability to scroll full width like in this:

    desired

    Is there a way to create that initial offset in a collection view using Swift 3?