![](/img/trans.png)
[英]Return storyboard cell size or ignore collectionview on sizeForItemAt delegate method
[英]Prevent sizeForItemAt from using the wrong cell size because of reuse for dynamic collectionView cell
我使用自動布局來動態計算collectionView單元的大小。 某些單元格在第一次滾動以查看端口時,正在使用重用單元格中的尺寸。 當我繼續滾動collectionView時,它們將被設置為正確的值。
在我的sizeForItemAt
,我有以下內容:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if let cachedSize = cachedHeightForIndexPath[indexPath] {
return cachedSize
}
if let cell = collectionView.cellForItem(at: indexPath) {
cell.setNeedsLayout()
cell.layoutIfNeeded()
let size = cell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
cachedHeightForIndexPath[indexPath] = size
print("value is \(size) for indexpath: \(indexPath)")
return size
}
return CGSize(width: ScreenSize.width, height: 0.0)
}
我進行了三個會話,第一部分的所有單元格的理論高度都等於88,其他所有部分的所有單元格的高度均等於104。
最初,只有第一部分可見。 從控制台,我可以看到單元的高度設置為預期的88.0。 當我滾動到其余部分時(第一部分將是不可見的,單元格將被重用),第二部分和第三部分中的某些單元格在第一次滾動到查看端口而不是104時將值88.0用作單元格的高度當我繼續滾動時,錯誤尺寸的單元將使用104作為尺寸。 我們如何強制所有像元重新計算高度,而不使用舊像元的高度。
你有正確的想法,但是當你通過調用衡量其內部約束電池systemLayoutSizeFitting
而不是調用, systemLayoutSizeFitting
在現有的細胞( collectionView.cellForItem
),你需要武裝自己,你配置相同的細胞模型 cellForItem
將配置它, 並且測量。
這是我的操作方法(與您的方法非常相似,只是有一個區別;另外,我將尺寸存儲在模型中):
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let memosize = self.sections[indexPath.section].itemData[indexPath.row].size
if memosize != .zero {
return memosize
}
self.configure(self.modelCell, forIndexPath:indexPath) // in common with cellForItem
var sz = self.modelCell.contentView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
sz.width = ceil(sz.width); sz.height = ceil(sz.height)
self.sections[indexPath.section].itemData[indexPath.row].size = sz // memoize
return sz
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.