Чтобы добавить пользовательскую метку выше каждой секции в UICollectionView, пожалуйста, следуйте ниже шаги
- Включить заголовок раздела в UICollectionViewCell
- Добавить новый файл типа UICollectionReusableView
- В раскадровке измените класс заголовка раздела в UICollectionViewCell на вновь добавленный файл типа UICollectionReusableView.
- Добавить метку в разделе заголовка UICollectionViewCell в раскадровке
Подключите метку в заголовке раздела в файл UICollectionReusableView
class SectionHeader: UICollectionReusableView {
@IBOutlet weak var sectionHeaderlabel: UILabel!
}
В ViewController добавить код ниже
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
if let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "SectionHeader", for: indexPath) as? SectionHeader{
sectionHeader.sectionHeaderlabel.text = "Section \(indexPath.section)"
return sectionHeader
}
return UICollectionReusableView()
}
Здесь «SectionHeader» - это имя файла, добавленного к типу UICollectionReusableView
Пример кода здесь: https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch08p462collectionViewFlowLayout/ch21p748collectionViewFlowLayout/ViewController.swift – matt