Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collectionview Fixed Cell Spacing

I've been looking for how to make UICollectionView have a fixed spacing between its cells, but have not found a solution so far.

I have a UICollectionView which consists of two columns, and all the cells have the same width, but they vary in height. I have only one section in this UICollectionView.

I have set the minimum spacing to 10(which is the value I want between cells vertically), but the system is seemingly randomly stretching the vertical space.

What I would like to achieve, is the effect Wikipedia for iPad has: different article tiles with the same width, but adjustable height according to need, yet all the cells are spaces evenly vertically. (I don't mind leaving space at the very end, but I don't want extra spaces in the middle)

How should I achieve this? I would accept third-party libraries if it is easy to migrate existing UICollectionViews(and it's open-source, of course).

like image 240
Nicholas Avatar asked Dec 20 '25 15:12

Nicholas


1 Answers

In swift 3, you can implement this delegate method for cell spacing in collectionView :

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize{
    // Give cell width and height
    return CGSize(width: 750, height: 320)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat{
    // splace between two cell horizonatally
    return 50
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat{
    // splace between two cell vertically
    return 100
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets{
    // give space top left bottom and right for cells
    return UIEdgeInsets(top: 0, left: 100, bottom: 100, right: 100)
}
like image 188
vikas prajapati Avatar answered Dec 23 '25 07:12

vikas prajapati



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!