ios - 如何拥有一个具有两个集合视图的视图控制器,但只有一个具有页眉/页脚视图?
问题描述
我的视图控制器中有两个集合视图,它们被设置为两者的委托和数据源。其中一个集合视图有一个已注册的补充视图作为其标题,它在我添加第二个集合视图之前将其出列并正确显示。现在使用第二个集合视图,viewForSupplementaryElementOfKind
由于第二个集合视图没有任何已注册的标头,因此会导致错误。如何确保仅在第一个集合视图上调用该函数?
解决方案
像这样为 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)
}
推荐阅读
- c++ - 在 VSCode 中编写的库要求是什么以及如何通过 browse.path 和设置“同步”我的目录
- typescript - Highstock / Angular-cli : TypeError: this.getChartData is not a function at I.afterSetExtreme
- javascript - PHP 标记内的内联 JavaScript 函数
- javascript - 如何用锚点击上的另一个部分替换页面上的一个部分?
- linux - 如何设置和记录 Jenkins 服务器关闭和启动的警报
- mysql - MySQL 加入来自文本类型库的特定子字符串
- go - 在所有集成测试之前运行
- linux - 从其他进程执行进程时的性能
- linux - Gnu并行卡住了,没有输出
- java - 当API通过JSON返回空值时,使用Moshi时有什么方法可以在Kotlin数据类中返回默认值