UICollectionView 自定义布局。不显示或查询补充视图

UICollectionView custom layout. Supplementary views are not shown or queried

我正在尝试为 UICollectionView 创建一个简单的自定义布局以编程方式使用(即没有 Interface Builder)。

我根据文档做所有事情:

  1. 子类 UICollectionViewLayout 并准备我的布局
  2. 覆盖layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath)和return对应的布局属性
  3. 添加 collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) 实现,其中我 return 我的补充观点

我的问题是两者都没有

collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath)

也不

layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath)

正在打电话,看不到我的补充意见

我已经仔细检查了我的布局和补充视图创建的实现,但我仍然无法让它工作。

显然有

是不够的
layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

哪些 return 属性用于补充视图。

中的补充视图还需要 return 属性
layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

我的错误是我只return在

中为单元格设置布局属性
layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

一旦我将补充视图的布局属性添加到值 return编辑者

layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?

我调用了我的数据源方法和补充视图 returned。

编辑:此答案涵盖 iOS10 SDK。我还没有尝试过早期版本

接受的答案很好,但一些示例代码会有所帮助:

override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {

    let layoutAttributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: elementKind, with: indexPath)

    if elementKind == UICollectionView.elementKindSectionHeader {
        layoutAttributes.frame = CGRect(x: 0.0, y: 0.0, width: contentWidth, height: headerHeight)
        layoutAttributes.zIndex = Int.max - 3
    }

    return layoutAttributes
}