Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resize a horizontal UICollectionView height based on its content in a UITableViewCell

I'm trying to place a UICollectionView in a UITableViewCell. I want to display comments in the UICollectionViewCells with paging. There might be more than one line in comments so I want to resize the UICollectionView if there are more than one line in comment label.

This is the demo project for the question. I would really appreciate it if you can fix the problem on this demo.

The cells will look like this.

enter image description here

I tried some answers but I couldn't achieve any progress. Can you tell me what I need to do step by step? Demo would be much better if you can share. Thank you.

like image 867
Sercan Avatar asked Oct 24 '18 13:10

Sercan


1 Answers

OK.. So I had the same problem... I fixed it with the following steps...

Create a height constraint outlet of the collection view, which you will set based on the dynamic content you have.

`@IBOutlet private(set) weak var collectionViewHeightConstraint: NSLayoutConstraint!`

Find the largest content model (which in your case would be the largest comment) and find the height of the largest collection view cell. This can be done with the following method.

private func getSizingCellHeight(for item: T.YourModel) -> CGFloat {
    guard let sizingCell = sizingCell else {
        return 0
    }

    sizingCell.frame.size.width = collectionViewItemWidth // This would be the width your collection view has
    sizingCell.prepareForReuse()

    // This is the method inside of your collection view cell, which lays out the content of the cell 
    sizingCell.configure(with: item)
    sizingCell.layoutIfNeeded()

    var fittingSize = UILayoutFittingCompressedSize
    fittingSize.width = collectionViewItemWidth

    let size = sizingCell.contentView.systemLayoutSizeFitting(
        fittingSize,
        withHorizontalFittingPriority: .required,
        verticalFittingPriority: .defaultLow
    )

    return size.height
}

Running the above method will give you the height of the largest cell, which you can use to the height constraint of the collectionView.

private func setCollectionViewHeight() {
    var largestHeight: CGFloat = 0

    //items would be your datasource for the collection view
    let items: [YourModel] = .... with some values
    if let items = items {
        for item in items {
            let height = getSizingCellHeight(for: item)
            if height > largestHeight {
                largestHeight = height
            }
        }
    }

    collectionViewHeightConstraint?.constant = largestHeight
}

This is actual working code which I have in my project.

From what I last remember, I followed Charlie's Article.

The Article also has a working demo on Github

like image 77
Harsh Avatar answered Nov 17 '22 14:11

Harsh