【问题标题】:Optional UICollectionView Header可选的 UICollectionView 标头
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 2012-09-18
      相关资源
      最近更新 更多