【发布时间】:2021-06-11 13:05:48
【问题描述】:
我在UICollectionViewDataSource 中实现了以下方法,以便为我的UICollectionView 部分返回一个标头。
但是,如果hasOthers 为真,我只想返回header 视图。在这种情况下,下面的代码会引发以下异常:
Exception NSException * "the view returned from -collectionView:viewForSupplementaryElementOfKind:atIndexPath (UICollectionElementKindSectionHeader,<NSIndexPath: 0xaa02564b411fe771> {length = 2, path = 0 - 0}) was not retrieved by calling -dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: or is nil (<UICollectionReusableView: 0x7ff43f577700; frame = (0 0; 0 0); layer = <CALayer: 0x6000026484a0>>)" 0x000060000321f240
我也无法从此方法返回 nil,因为它不返回 Optional。
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if kind == UICollectionView.elementKindSectionHeader {
if !hasOthers {
return UICollectionReusableView()
}
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as? OrderCVHeaderView {
sectionHeader.backgroundColor = .white
return sectionHeader
}
}
return UICollectionReusableView()
}
我在实现时遵循了这个例子:
https://stackoverflow.com/a/57666316/4909000
只有当hasOthers 为真时,我如何才能返回可选标头?
【问题讨论】:
标签: ios swift uicollectionview header uicollectionviewlayout