2
votes

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

2
Why you are set UICollectionViewFlowLayout.automaticSize, comment this line and try itNaresh
Just this line is enough flowLayout.estimatedItemSize = CGSize(width: (UIScreen.main.bounds.width / 2), height: 2000.0)Naresh
@YagneshDobariya: No luck.KP26
Were you able to resolve this?Luke Irvin

2 Answers

1
votes

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

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
}