Search code examples
iosswiftuser-interfaceresizecollectionview

Collection View Dynamic size (DID THE FOLLOWING BUT DIDNOT WORK)


I did what this answer said but it did not work why?

How to adjust height of UICollectionView to be the height of the content size of the UICollectionView?

but there is a problem its not resizing what am i missing out


Solution

  • I have also faced same issue so I did another approach. You need to add width constraint and you need to set it constant in systemLayoutSizeFitting function.

    The main thing you should be careful about that is add all subviews to contentView of cell and also the last subview must has a constraint to bottom of contentView like the autoResizing TableViewCell

    class ABCCell: UICollectionViewCell {
    
    lazy var width: NSLayoutConstraint = {
        let width = contentView.widthAnchor.constraint(equalToConstant: bounds.size.width)
        width.isActive = true
        return width
    }()
    
    override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
        width.constant = bounds.size.width
        return contentView.systemLayoutSizeFitting(CGSize(width: targetSize.width, height: 1))
    }
    }