Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView dynamic cell height (Pinterest layout)

I'm trying to achieve Pinterest layout in my app

and I used the following delegate method to achieve that and set the cell height dynamically

 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 white spaces which I don't know how to remove.

How can I fix this?

like image 746
nouf Avatar asked Jan 17 '17 09:01

nouf


1 Answers

You can view the raywenderlich tutorial for this:

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

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

In PinterestLayout.swift, do following changes:

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

to

 guard let collectionView = collectionView else {
        return
    } 

// This file name may be differ from yours

In PhotoStreamViewController.swift, add following code:

   override func collectionView(_ collectionView:  UICollectionView, willDisplay cell: UICollectionViewCell,  forItemAt indexPath: IndexPath) {
      if (indexPath.row == photos.count - 1 ) {
     //it's your last cell

     // Add more data to the array according your requirement

     // After adding data reload collection view
        collectionView.reloadData()
        
    }
}
like image 145
H S Progr Avatar answered Oct 19 '22 15:10

H S Progr