ios - UICollectionView 自定义布局单元格类型相关属性
问题描述
我的集合视图具有动态布局和多种单元格/标题类型,我想仅将背景颜色应用于某些类型的标题。我尝试IndexPath
在运行时确定这些标头的方法是:
class MyCustomLayout: UICollectionViewFlowLayout {
private var backgroundAttrs = [UICollectionViewLayoutAttributes]()
override func prepare() {
super.prepare()
guard let numberOfSections = collectionView?.numberOfSections else { return }
backgroundAttrs.removeAll()
for section in 0 ..< numberOfSections {
if let header = collectionView?
.supplementaryView(forElementKind: UICollectionElementKindSectionHeader,
at: IndexPath(item: 0, section: section)) as? HeaderThatNeedsBackground,
let attr = getBackgroundAttribute(forSection: section) {
backgroundAttrs.append(attr)
}
}
}
...
}
supplementaryView(forElementKind:, at:)
一直给我nil
,所以循环永远不会执行。我的猜测是此时单元格尚未实例化?任何关于如何根据单元格/标题类型有选择地应用布局属性的建议将不胜感激
解决方案
首先,您不应该调用检索单元或补充视图的集合视图方法,因为集合视图使用布局(您正在实现的布局)来检索这些元素的信息。UICollectionViewLayout
您可以在此链接中阅读如何正确子类化 a 。
在您的特定情况下,您需要覆盖该功能:
layoutAttributesForSupplementaryView(ofKind:at:)
推荐阅读
- javascript - 如何简化 _uniq 函数中的代码?
- mongodb - 将 mongo db 从连接字符串恢复到本地数据库
- python - 在 Python 中评估单词字符串的辅音/元音组成
- spring - 级联的 OneToOne 映射 = CascadeType.DETACH
- sql - 基于函数依赖的数据库规范化
- docker-compose - 无法从 gitlab 克隆存储库(traefik 反向代理后面的 docker)
- spring - WebSocket java.lang.UnsupportedOperationException
- python - 在导入包“nltk”后但在执行“nltk.downloader”之前在 sys.modules 中找到“nltk.downloader”;
- docker - 在 Dockerfile 中指定 ARG 中的多个文件到 COPY
- refit - 使用 Uno 平台改装 5.0 失败并出现“MissingMethodException”