假设你像这样设置你的collectionView
您使用的是默认流布局。因此您可以在页眉和页脚中添加标签。并在页脚标签中,将其标记设置为 1001(或您喜欢的任何数字)。
header 的标识符是“header”,footer 是“footer”。
UICollectionElementKindSectionHeader 在流布局类中定义(查看文档。)
现在您可以像这样重新加载页眉和页脚:
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView{
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: (kind == UICollectionElementKindSectionHeader ? "header": "footer"), for: indexPath)
// Configure the cell
return cell
}
当您尝试更改页脚中标签的内容时,您无需刷新页脚。您可以在应用程序中的任何位置调用以下命令。为了方便起见,我称它为一个单元格来运行测试
.
override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool {
let footView = collectionView.supplementaryView(forElementKind: UICollectionElementKindSectionFooter, at: IndexPath.init(row: 0, section: 1))
if let label = footView?.viewWithTag(1001) as? UILabel{
label.text = "AnyThing"
}
这里我使用的是 IndexPath.init(row: 0, section: 1),这是第二个部分。
现在你看到了结果。
这是一个最简单的例子。 CollectionView 可能非常复杂,值得一本书用于各种应用程序和示例。希望对您有所帮助。