首页 > 解决方案 > 如何拥有一个具有两个集合视图的视图控制器,但只有一个具有页眉/页脚视图?

问题描述

我的视图控制器中有两个集合视图,它们被设置为两者的委托和数据源。其中一个集合视图有一个已注册的补充视图作为其标题,它在我添加第二个集合视图之前将其出列并正确显示。现在使用第二个集合视图,viewForSupplementaryElementOfKind由于第二个集合视图没有任何已注册的标头,因此会导致错误。如何确保仅在第一个集合视图上调用该函数?

标签: iosswiftuicollectionview

解决方案


像这样为 UICollectionView 创建一个简单而简短的自定义子类:

class CustomCollectionView : UICollectionView {
    let showFooter : Bool
    let showHeader : Bool

    init(showHeader:Bool,showFooter:Bool) {
        self.showFooter = showFooter
        self.showHeader = showHeader
        //Create a custom UICollectionViewLayout and frame according to your requirement here (You can send parent ViewControllers frame as a param in the init above too)
        super.init(frame: CGRect.zero, collectionViewLayout: UICollectionViewLayout.init())
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

现在只需使用 showHeader 和/或 showFooter 将第一个 CollectionView 初始化为 true 和其他相应的。您现在需要在请求补充视图的委托回调中执行以下操作:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    guard let collectionView = collectionView as? CustomCollectionView else {
        return UICollectionReusableView.init(frame: .zero)
    }

    switch kind {
    case UICollectionView.elementKindSectionFooter:
        if collectionView.showFooter {
                //Dequeue a footer and return
        }
    case UICollectionView.elementKindSectionHeader:
        if collectionView.showHeader {
                //Dequeue a header and return
        }
    default:
        return UICollectionReusableView.init(frame: .zero)
    }
    return UICollectionReusableView.init(frame: .zero)
}

推荐阅读