Dynamic cell height of UICollectionView (Pinterest layout)

I am trying to achieve Pinterest layout in my application

and for this I used the following delegation method and dynamically set the cell height

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let boundingRect = CGRect(x: 0, y: 0, width: self.view.frame.size.width / 2 - 20, height: CGFloat(MAXFLOAT)) let data = articles[indexPath.row] let rect = AVMakeRect(aspectRatio: (data.coverImage?.size)!, insideRect: boundingRect) return CGSize(width: rect.width, height: rect.height + 120) // Added 120 for a description I will add later } 

But I got the following result:

Here

The gray background is the background of the cell, you can see that each cell has its own height (as expected) but there are extra spaces that I don’t know how to remove.

How can i fix this?

+9
swift pinterest uicollectionviewcell
source share
2 answers

The layout of the UICollectionView incorrect. Remove the spacing between cells and the spacing between columns from either the storyboard or using the CollectionViewDelegateFlowLayout method.

  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return CGFloat()// Your Value } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return CGFloat()// Your Value } 
0
source share

You can view the raywenderlich manual for this:

https://www.raywenderlich.com/164608/uicollectionview-custom-layout-tutorial-pinterest-2

If you want to load new data when you reach the last cell, you need to edit some code.

In PinterestLayout.swift, make the following changes:

  guard cache.isEmpty == true, let collectionView = collectionView else { return } 

in

  guard let collectionView = collectionView else { return } 

// This file name may differ from yours.

In PhotoStreamViewController.swift add the following code:

  override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if (indexPath.row == photos.count - 1 ) { //it your last cell // Add more data to the array according your requirement // After adding data reload collection view collectionView.reloadData() } } 
0
source share

All Articles