简体   繁体   中英

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM