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

问题描述 投票:1回答:2

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

我根据文档做了一切:

  1. 子类UICollectionViewLayout并准备我的布局
  2. 覆盖layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath)并返回相应的布局属性
  3. 在我返回补充视图的地方添加collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath)实现

我的问题是collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath)layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath)都没有被调用,所以我看不到我的补充意见。

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

ios uicollectionview uikit uicollectionviewlayout
2个回答
4
投票

显然,让layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?返回补充视图的属性是不够的。

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

我的错误是我只返回layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?中单元格的布局属性

一旦我将补充视图的布局属性添加到layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?返回的值中,我就会调用我的数据源方法并返回补充视图。

编辑:这个答案涵盖iOS10 SDK。我没有试过早期版本


0
投票

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

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
}
© www.soinside.com 2019 - 2024. All rights reserved.