Search code examples
iosiphoneswiftxcode9

IOS, swift - UICollectionReusableView not working


I want to make collection view header but it isn't working.

Storyboard

enter image description here

On device

enter image description here

My code below is not working, print("ssssss") don't show.

override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        print("sssssss")
        switch kind {

        case UICollectionElementKindSectionHeader:

            let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind,
                                                                             withReuseIdentifier: "mypageheader",
                                                                             for: indexPath) as! MyPageHeaderView
            headerView.backgroundColor = UIColor.blue;
            return headerView

        default:

            assert(false, "Unexpected element kind")
        }
    }

on viewDidLoad()

self.collectionView?.register(MyPageViewController.self,forSupplementaryViewOfKind: UICollectionElementKindSectionHeader,withReuseIdentifier: "mypageheader")

Solution

  • You should implement this delegate method:

    func collectionView(_ collectionView: UICollectionView,
                        layout collectionViewLayout: UICollectionViewLayout,
                        referenceSizeForHeaderInSection section: Int) -> CGSize {
    
        return CGSize(width: collectionView.bounds.width, height: 100)
    }
    

    Don't forget to setup the delegate of your collectionView in the storyboard!