Ios 自定义集合视图布局的动态单元格高度

Ios 自定义集合视图布局的动态单元格高度,ios,Ios,我有一个集合视图,它使用自定义布局。我试图动态计算高度,但问题是在cellForItemAt:indexPath之前调用sizeForItemAt:indexPath 我的手机在cellForItemAt中加载。但由于sizeForItemAt在cellForItemAt之前调用,所以我不能使用我计算的高度 我知道使用苹果的FlowLayout,我可以为布局设置estimatedItemSize。我不知道如何使用自定义布局 请告知。谢谢大家! 我也有同样的问题,我的应用程序使用动态高度的自定义布

我有一个集合视图,它使用自定义布局。我试图动态计算高度,但问题是在cellForItemAt:indexPath之前调用sizeForItemAt:indexPath

我的手机在cellForItemAt中加载。但由于sizeForItemAt在cellForItemAt之前调用,所以我不能使用我计算的高度

我知道使用苹果的FlowLayout,我可以为布局设置estimatedItemSize。我不知道如何使用自定义布局


请告知。谢谢大家!

我也有同样的问题,我的应用程序使用动态高度的自定义布局。我发现,对于不扩展
UICollectionViewFlowLayout
或任何其他默认布局的自定义布局,动态高度将不起作用,因为根据Apple文档(您可能已经注意到),对于完全自定义的布局,您必须预定义所有单元格X、Y、width,高度在传感器负载之前,甚至在您有数据之前。 我将自定义布局更改为子类
UICollectionViewFlowLayout
,并实现了
UICollectionViewDelegateFlowLayout
。当调用此方法时,单元尚未加载,但单元的数据可用,因为我知道单元的外观(假设您使用的是单元原型),我可以使用其数据和索引计算单元的宽度和高度,如下所示:

func collectionView(_ collectionView: UICollectionView, 
         layout collectionViewLayout: UICollectionViewLayout, 
             sizeForItemAt indexPath: IndexPath) -> CGSize {
   // get the cell's data 
   if let data = self.fetchedResultsController.fetchedObjects![indexPath.row] as? YourDataType {
      // carculate the cell width according to cell position
      let cellWidth = carculateCellWidth(indexPath.row) 
      var cellHeight : CGFloat = 0
      // assuming the cell have a label, set the label to have the same attributes as set in the storyboard or set programmatically
      let label = UILabel()  
      label.numberOfLines = 0
      label.font = UIFont.preferredFont(forTextStyle: .subheadline)
      label.text = data.text
      // carculate the height of the cell, assuming here the label width equal the cell width minus 10px left and right padding. 
      cellHeight += label.systemLayoutSizeFitting(CGSize(width:cellWidth-20, height: CGFloat(Float.greatestFiniteMagnitude))).height
      return CGSize(width: cellWidth, height: cellHeight)
   }
   return .zero
}

这不是一个非常优雅的解决方案,但很有效。

谢谢,非常感谢!