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

时间:2018-01-24 22:39:53

标签: ios

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

我的单元格被加载到cellForItemAt中。但是因为sizeForItemAt是在cellForItemAt之前调用的,所以我无法使用我计算出的高度。

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

请指教。谢谢!

1 个答案:

答案 0 :(得分:1)

我有同样的问题,我的应用程序使用动态高度的自定义布局。我发现,对于不扩展UICollectionViewFlowLayout或任何其他默认布局的自定义布局,动态高度将无法工作,因为根据Apple文档(并且您可能已注意到)使用完全自定义布局,您必须预先定义所有单元格X,Y,宽度,高度单元格加载之前,甚至在您拥有数据之前。 我将自定义布局更改为子类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
}

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

相关问题