I want my sections in the UICollectionView
to have a header with an image.
I have followed these steps:
Did you add UICollectionViewDelegateFlowLayout in current interface? This worked for me.
@interface MyViewController () <UICollectionViewDelegateFlowLayout>
Swift:
class MyViewController: UICollectionViewDelegateFlowLayout {
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 {}
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.
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.
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 {
...