UICollectionReusableView method not being called

后端 未结 11 715
暗喜
暗喜 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:37

    You answered the question, but in words I understand better:

    To make the method being called, add these methods:

    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
        return CGSizeMake(60.0f, 30.0f);
    }
    
    - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
        return CGSizeMake(60.0f, 30.0f);
    }
    

    ...and go from there.

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

    I have the same issue. I have added referenceSizeForFooterInSection but then also viewForSupplementaryElementOfKind not getting called. I have added this code in viewDidLoad() and it worked for me:

    if let flowLayout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        flowLayout.sectionFootersPinToVisibleBounds = true   
    }
    
    0 讨论(0)
  • 2021-01-31 13:42

    Swift 3.0 (xcode 8.2.1)

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width:collectionView.frame.size.width, height:30.0)
    }
    
    0 讨论(0)
  • 2021-01-31 13:43

    It seems that you have to give your header a non-zero size or collectionView:viewForSupplementaryElementOfKind:atIndexPath isn't called. So either set the headerReferenceSize property of the flow layout like so:

    flowLayout.headerReferenceSize = CGSizeMake(self.collectionView.frame.size.width, 100.f);
    

    Swift 5+

    flowLayout.headerReferenceSize = CGSize(CGSize(width: self.collectionView.frame.size.width, height: 100))
    

    or, implement collectionView:layout:referenceSizeForHeaderInSection if you want to vary the size by section.

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

    The above code worked for me

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

    Swift 4 Xcode 9.1 Beta 2

    Add @objc

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

    Credits: https://medium.com/@zonble/your-delegation-methods-might-not-be-called-in-swift-3-c6065ed7b4cd

    0 讨论(0)
提交回复
热议问题