首页 > 解决方案 > viewForSupplementaryElementOfKind 没有被调用

问题描述

我已经声明了如下的集合视图

lazy var collectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.itemSize  = UICollectionViewFlowLayout.automaticSize
        layout.minimumLineSpacing = 52
        layout.sectionInset = UIEdgeInsets(top: 25, left: 0, bottom: 30, right: 0)
        var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        collectionView.register(XXXCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        collectionView.register(XXXHeaderViewCell.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerIdentifier)
        collectionView.delegate = self
        return collectionView
    }()

并在委托下实现,控制权仅来自referenceSizeForHeaderInSection方法而不是viewForSupplementaryElementOfKind

public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerIdentifier, for: indexPath)
        return headerView
    }

public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let size = CGSize(width: self.collectionView.bounds.width, height: 200)
        return size
    }

非常感谢任何帮助。

标签: iosuicollectionview

解决方案


我遇到了同样的问题,然后想出了一个解决方案。

尝试在@objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:)您的func collectionView(viewForSupplementaryElementOfKind:at:).

似乎 obj-C 和 Swift 有不同的名称。看看最后一个参数,在 obj-C 上我们有atIndexPath,而在 Swift 上我们只有at.

那有帮助吗?


推荐阅读