Подтвердить что ты не робот

Как добавить заголовок раздела в UICollectionView?

Мне нужен ярлык над каждым разделом в моем представлении коллекции. Я попробовал просто перетащить ярлык в мое пространство заголовка над моей ячейкой прототипа, но каждый раз, когда я запускаю приложение, метка не видна.

Любая помощь?

4b9b3361

Ответ 1

Чтобы добавить пользовательскую метку над каждым разделом в UICollectionView, выполните следующие шаги

  1. Включить заголовок раздела в UICollectionViewCell

enter image description here

  1. Добавить новый файл типа UICollectionReusableView
  2. В раскадровке измените класс заголовка раздела в UICollectionViewCell на вновь добавленный файл типа UICollectionReusableView.
  3. Добавить метку в заголовке раздела UICollectionViewCell в раскадровке
  4. Подключите ярлык в заголовке раздела к файлу UICollectionReusableView

    class SectionHeader: UICollectionReusableView {
        @IBOutlet weak var sectionHeaderlabel: UILabel!
    }
    
  5. В 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

Ответ 2

Реализовать collectionView:viewForSupplementaryElementOfKind:atIndexPath: и предоставить удаленный UICollectionElementKindSectionHeader, содержащий вашу метку. Если это макет потока, убедитесь, что вы также установите headerReferenceSize или вы все равно ничего не увидите.

Ответ 3

От @david72 ответ

Вам необходимо выполнить следующие действия:

  1. Включите представление верхнего/нижнего колонтитула раздела в раскадровке.
  2. Реализуйте метод collectionView:viewForSupplementaryElementOfKind.

Для получения более подробной информации смотрите здесь

Ответ 4

Если вам нужно программное решение в Swift 4.2, вы можете сделать следующее:

  1. Настройте UICollectionViewDelegate и UICollectionViewDelegateFlowLayout
  2. Создайте пользовательские подклассы UICollectionReusableView с любыми представлениями, которые вы хотите определить. Здесь один для заголовка, вы можете создать другой для нижнего колонтитула с другими характеристиками:

    class SectionHeader: UICollectionReusableView {
         var label: UILabel = {
         let label: UILabel = UILabel()
         label.textColor = .white
         label.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
         label.sizeToFit()
         return label
     }()
    
    override init(frame: CGRect) {
         super.init(frame: frame)
    
         addSubview(label)
    
         label.translatesAutoresizingMaskIntoConstraints = false
         label.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
         label.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 20).isActive = true
         label.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
    }
    
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
  3. Реализуйте метод viewForSupplementaryElementOfKind с помощью пользовательских представлений:

    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { 
        if kind == UICollectionView.elementKindSectionHeader {
             let sectionHeader = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! SectionHeader
             sectionHeader.label.text = "TRENDING"
             return sectionHeader
        } else { //No footer in this case but can add option for that 
             return UICollectionReusableView()
        }
    }
    
  4. Реализуйте методы referenceSizeForHeaderInSection и referenceSizeForFooterInSection. Метод заголовка, показанный ниже, например:

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