KP26
KP26

Reputation: 283

UICollectionview cell with dynamic height and half width

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

Upvotes: 2

Views: 1967

Answers (2)

M. Mansuelli
M. Mansuelli

Reputation: 1113

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
}

Upvotes: 0

Awais Mobeen
Awais Mobeen

Reputation: 852

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

Upvotes: 1

Related Questions