![](/img/trans.png)
[英]Configuring dynamic cell height with a custom collection view layout swift
[英]Dynamic Cell Height for Custom Collection View Layout
我有一個使用自定義布局的集合視圖。 我正在嘗試動態計算高度,但是問題是在cellForItemAt:indexPath之前調用了sizeForItemAt:indexPath。
我的單元格加載到cellForItemAt中。 但是由於sizeForItemAt在cellForItemAt之前被調用,所以我不能使用計算出的高度。
我知道使用Apple的FlowLayout可以只為布局設置estimateItemSize。 我不確定如何使用自定義布局。
請指教。 謝謝!
我遇到了同樣的問題,我的應用程序使用具有動態高度的自定義布局。 我發現,使用不會擴展UICollectionViewFlowLayout
或其他任何默認布局的自定義布局,動態高度將不起作用,因為根據Apple文檔(以及您可能注意到的那樣),使用完全自定義布局的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
}
這不是一個非常優雅的解決方案,但它可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.