Dynamic UICollectionView inside dynamic UITableVie

2020-06-27 09:28发布

问题:

I have a collection view that is dynamic and can have any number of cells in it. It is positioned inside a table view cell.

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

My table view is correctly configured to be dynamic because the other cells work fine so the issue is not there.

Here is what I currently have... As you can see there is no collection view below

This is what my desired out come is... (Forcing a height constraint on the collection view)

I have configured constraints on all sides of the collection view correctly, as it works when I give a fix height constraint. But this defeats the object of a dynamic collection view...

I have linked an outlet to the UICollectionViewFlowLayout and set an estimated cell size and given the cell the correct constraints on the label inside as you can see in the image where I forced the height constraint.

回答1:

Create a subclass for collectionView and override intrinsicContentSize.

class DynamicCollectionView: UICollectionView {
  override func layoutSubviews() {
    super.layoutSubviews()
    if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
        self.invalidateIntrinsicContentSize()
     }
  }

   override var intrinsicContentSize: CGSize {
    return collectionViewLayout.collectionViewContentSize
   }
}
  1. In Interface builder change the class of your collectionView to DynamicCollectionView (subclass UICollectionView).

  2. Set estimated cell size of UICollectionViewFlowLayout.

        flowLayout.estimatedItemSize = CGSize(width: 1,height: 1)