Search code examples
iosswiftuicollectionviewuicollectionviewcell

UICollectionViewCell With 2 column grid and dynamic height


I'm trying to have collection view with 2 column but dynamic height. I have used Autolayout and given required constraints to the Cell

By this way I can calculate the dynamic height but its column grids fails.

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MenuListCollectionViewCell
       cell.frame.size.width = collectionView.frame.width/2
    cell.menuList = self.menuList[indexPath.row]
    let resizing = cell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize, withHorizontalFittingPriority: UILayoutPriority.required, verticalFittingPriority: UILayoutPriority.fittingSizeLevel)
       return resizing
}

This is how I want it to look


Solution

  • Not sure what you mean by "its column grid fails".

    Anyway, you need to write a custom collection view layout. The default one (UICollectionViewFlowLayout) allows you to change height of the cells by providing the sizeForItemAt, but that won't change the behavior of the layout that will always arrange cells in rows of the same height (the height of the highest cell).

    If I understood correctly, you just want the same layout of this raywenderlich tutorial.

    Basically:

    1. Create a subclass of UICollectionViewLayout implementing it's methods:
    2. collectionViewContentSize: return width and height of the collection view content
    3. prepare: where you can calculate the sizes of cells and collectionView content
    4. layoutAttributesForElements: where you return an array of UICollectionViewLayoutAttributes in the given rect
    5. layoutAttributesForItem: where you return the same kind of attributes, this time specific for an item
    6. assign an object of this class to the collection view layout property