UICollectionView Self Sizing Cells with Auto Layout

前端 未结 16 2069
野性不改
野性不改 2020-11-22 05:58

I\'m trying to get self sizing UICollectionViewCells working with Auto Layout, but I can\'t seem to get the cells to size themselves to the content. I\'m having

16条回答
  •  清歌不尽
    2020-11-22 06:11

    The example method above does not compile. Here is a corrected version (but untested as to whether or not it works.)

    override func preferredLayoutAttributesFittingAttributes(layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes 
    {
        let attr: UICollectionViewLayoutAttributes = layoutAttributes.copy() as! UICollectionViewLayoutAttributes
    
        var newFrame = attr.frame
        self.frame = newFrame
    
        self.setNeedsLayout()
        self.layoutIfNeeded()
    
        let desiredHeight: CGFloat = self.contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height
        newFrame.size.height = desiredHeight
        attr.frame = newFrame
        return attr
    }
    

提交回复
热议问题