Search code examples
swift3uicollectionview

How to count number of uicollectionview's rows in swift


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


Solution

  • 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))
    }