CollectionView dynamic height with Swift 3 in iOS

后端 未结 4 1438
说谎
说谎 2020-12-18 06:16

Recently, I\'m trying to do some projects for practicing. So I watched the course \"Developing Apps for iOS\", Stanford University, CS193P, 2017.

And now, I\'m doing

4条回答
  •  醉梦人生
    2020-12-18 06:46

    Provide estimatedSize to your UICollectionViewLayout.

    The estimated size should be the size shown in the size inspector of your xib.

    collectionViewLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: 50)
    

    Override the method preferredLayoutAttributesFitting(_:) in your 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
    }
    

    Your collection view cell will now have dynamic size as per the content.

提交回复
热议问题