UICollectionReusableView method not being called

后端 未结 11 716
暗喜
暗喜 2021-01-31 13:13

I want my sections in the UICollectionView to have a header with an image.

I have followed these steps:

  • at the storyboard, assigned a header a
相关标签:
11条回答
  • 2021-01-31 13:50

    Did you add UICollectionViewDelegateFlowLayout in current interface? This worked for me.

    @interface MyViewController () <UICollectionViewDelegateFlowLayout>

    Swift:

    class MyViewController: UICollectionViewDelegateFlowLayout {

    0 讨论(0)
  • 2021-01-31 13:50

    My problem was that in swift 3, the name of the viewForSupplementaryElementOfKind function has changed slightly from any posts that were on stack overflow. Hence, it was never getting called. Make sure that, if you're in swift 3, you're delegate function matches:

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {}
    
    0 讨论(0)
  • 2021-01-31 13:55

    There is the swift version :

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        let size = CGSize(width: 400, height: 50)
        return size
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        let size = CGSize(width: 400, height: 50)
        return size
    }
    

    XCode (version 7.3.1 ) does not propose these methods in autocomplete !

    If you just want a header, just keep the header method.

    0 讨论(0)
  • 2021-01-31 13:57

    For me, in Swift 4.2, func collectionView(collectionView:kind:indexPath:) -> UICollectionReusableView was never being called. This was for a collection view in a UIViewController. I noticed the existing collection view functions were qualified with @objc, and that the UICollectionView had not adopted the UICollectionViewDataSource and UICollectionViewDelegate protocols. As soon as I adopted the protocols, I got errors that the collection view functions did not match the protocol. I corrected the function syntax, removed the qualifiers, and the section headers started working.

    0 讨论(0)
  • 2021-01-31 13:59

    If you've got a generic subclass then you must take care to specify ObjC delegate method name if it's different then Swift name (https://bugs.swift.org/browse/SR-2817).

    @objc (collectionView:viewForSupplementaryElementOfKind:atIndexPath:)
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    ...
    
    0 讨论(0)
提交回复
热议问题