2

I need to determine uicollectionview's height.

let layout = contactCollectionView.collectionViewLayout
let heightSize = String(Int(layout.collectionViewContentSize.height))

The above solution works on some situations in my project. In this specific situation I need to count number of rows and then multiple it with a number to find height.

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // height = (count rows) * 30 . every cell height is 30 
        // every cell has different width.
        return (presenter?.selectedContact.count)!
    }

How can I find number of rows?

Update

Look at the image. enter image description here

This is my collectionView. Every cell has different width(because it is string). So It has different rows. The width of this collectionView is width of view.frame

Community
  • 1
  • 1
Amir Shabani
  • 690
  • 2
  • 14
  • 36

1 Answers1

5

You can compare if the collectionView's width is greater than total previous width(s) then you increment rowCounts by one. I am assuming you are implementing UICollectionViewDelegateFlowLayout methods and per each cell you know the dynamic width at the moment. if you won't know the width at that moment, you can also calculate the width of string that would take with considering UIfont along with other stuff in each cell.

Here is a reference how to calculate the width of a string https://stackoverflow.com/a/30450559/6106583

Something like below

//stored properties 
var totalWidthPerRow = CGFloat(0)
var rowCounts = 0   
let spaceBetweenCell = CGFloat(10) // whatever the space between each cell is 


func collectionView(_collectionView:UICollectionView, layoutcollectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
     
   let collectionViewWidth = view.frame.width 
   let dynamicCellWidth = //whatever you calculate the width 
   totalWidthPerRow += dynamicCellWidth + spaceBetweenCell
         

   if (totalWidthPerRow > collectionViewWidth) {
      rowCounts += 1
      totalWidthPerRow = dynamicCellWidth + spaceBetweenCell
   }

  return CGSizeMake(dynamicCellWidth , CGFloat(30))
}
    
   
Matin Kajabadi
  • 3,414
  • 1
  • 17
  • 21
  • 4
    This worked really for me with a few tweaks. Instead of using sizeForItemAt, I performed it in cellForItemAt where I could access each cells text width. I also started the rowCounts = 1, reset rowCounts and totalWidthPerRow when adding or subtracting new cells, and added a heightconstraint outlet from the collectionView which was made equal to rowCounts * rowHeight. Thanks Matt! – Trevor May 08 '18 at 11:45