2

Im trying to create collection view (Expected View) with half width and dynamic height based on given text.

I am trying to achieve this by (Code in ViewController)

    let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.width / 2), height: 2000.0)
    flowLayout.itemSize = UICollectionViewFlowLayout.automaticSize

And (Code in UICollectionviewCell)

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    setNeedsLayout()
    layoutIfNeeded()
    let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
    var frame = layoutAttributes.frame
    frame.size.height = ceil(size.height)
    layoutAttributes.frame = frame
    return layoutAttributes 
}

By using the above code, I can achieve to create collectionview Actual view (half width and dynamic height). But collection view cell height not equal to the adjacent. Actually this collection view cell height should be same as adjacent cell height(which is having the maximum height). How to update the cell size based on the adjacent cell size?

Thanks in advance

KP26
  • 283
  • 3
  • 14

2 Answers2

1

Use UICollectionViewDelegateFlowLayout

  func collectionView(_ collectionView: UICollectionView, layout 
collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: 
IndexPath) -> CGSize 
{
//let padding: CGFloat =  5
    let collectionViewSize = collectionView.frame.size.width / 2
    return CGSize(width: collectionViewSize , height: 2000 )
}
Awais Mobeen
  • 733
  • 11
  • 19
  • The above code makes the all cells in collectionview with height 2000. That is not the case here. – KP26 Nov 12 '19 at 14:59
  • you may change the height according to text that would be in that specific item as we did in a chat view this might help https://stackoverflow.com/questions/446405/adjust-uilabel-height-depending-on-the-text – Awais Mobeen Nov 13 '19 at 10:19
0

Add this code in your CollectionViewCell class:

override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
    setNeedsLayout()
    layoutIfNeeded()
    let size = contentView.systemLayoutSizeFitting(layoutAttributes.size)
    var newFrame = layoutAttributes.frame
    newFrame.size.height = ceil(size.height)
    newFrame.size.width = UIScreen.main.bounds.width / 2
    layoutAttributes.frame = newFrame
    return layoutAttributes
}
M. Mansuelli
  • 1,083
  • 9
  • 19