user7556668
user7556668

Reputation:

CollectionView. Maximum distance between Item. Swift 3

I know there is only minimum spacing between items and you can achieve that via size inspector or

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets

Indeed on the simulator on SE my items are shown like in the image below. enter image description here

But when I run on a larger simulator my distance between cell items is increasing and aren t showing as expected.

Is there any method to set like a maximum size between them ?

Upvotes: 1

Views: 356

Answers (1)

Ahmad F
Ahmad F

Reputation: 31655

Logically, there is another factor that you should keep in mind for setting the space between the items in your collection view, which is the size of the cell. If you are getting the cell as is (with its default size) -and my assumption is that's your case-, it would be statically dequeued in the collection view, i.e the size of the cell would be as is.

So, what you should do is to tell what is the desired size (width) of the cells to be displayed in the collection view, by conforming to UICollectionViewDelegateFlowLayout and implementing collectionView(_:layout:sizeForItemAt:):

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // let's assume that each row in the collection view should contains 3 cells:
    let desiredWidth = collectionView.frame.width / 3

    // height is also equals to the width to be a square...
    return CGSize(width: desiredWidth, height: desiredWidth)
}

At this point if you are setting the minimum space between items to zero, each row should contains three cells with no space between them.

If you are aiming to set a little space between the cells, you should reflect it when declaring the desired width for the cell, for example:

// since each row contains 3 cells, subtracting 2 from each cell width
// means it would be 6 points (3 * 2) divided at the whole row (2 spaces, 3 points for each)
let desiredWidth = collectionView.frame.width / 3 - 2

Upvotes: 0

Related Questions