可选的 UICollectionView 标题

问题描述

我在 UICollectionViewDataSource 中实现了以下方法,以便为我的 UICollectionView 部分返回标题

但是,如果 header 为真,我只想返回 hasOthers 视图。在这种情况下,以下代码会引发以下异常:

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 为 true 时,我如何才能返回可选标头?

解决方法

文档说:此方法必须始终返回有效的视图对象。如果在特定情况下不需要补充视图,则布局对象不应为该视图创建属性。或者,您可以通过将相应属性的 isHidden 属性设置为 true 或将属性的 alpha 属性设置为 0 来隐藏视图。 要在流布局中隐藏页眉和页脚视图,您还可以设置这些视图的宽度和高度到 0。