Заголовки разделов в UICollectionView, появляется только первый - PullRequest
1 голос
/ 19 апреля 2019

Я создал класс для заголовка раздела и загружаю его в свой UICollectionView.Я могу отобразить первый заголовок (хотя странно, см. Ниже), однако любые последующие заголовки разделов не заполнены.На размер ссылаются, но содержимое (цвет фона, метка) не появится.

А также еще ... один заголовок раздела, который отображается, отображается с отступом прибл.150px без видимой причины.Центры заголовков выровнены по умолчанию?Если так, как бы я выровнять их?

Мой класс заголовка раздела:

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    switch kind {
    case UICollectionView.elementKindSectionHeader:
        let section = indexPath.section
        switch section {
        case 0:
            let tagsHeader = searchCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TagsHeaderView", for: indexPath) as! SectionHeaderView
            tagsHeader.headerString = "Recent Tags"
            tagsHeader.backgroundColor = .green
            return tagsHeader
        default:
            let tagsHeader = searchCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TypeHeaderView", for: indexPath) as! SectionHeaderView
            tagsHeader.headerString = "Type"
            tagsHeader.backgroundColor = .blue
            return tagsHeader
        }
    default:
        return UICollectionReusableView()
    }
}

В моем UICollectionView

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    switch kind {
    case UICollectionView.elementKindSectionHeader:
        let section = indexPath.section
        switch section {
        case 0:
            let tagsHeader = searchCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TagsHeaderView", for: indexPath) as! SectionHeaderView
            tagsHeader.headerString = "Recent Tags"
            tagsHeader.backgroundColor = .green
            return tagsHeader
        default:
            let tagsHeader = searchCollectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "TypesHeaderView", for: indexPath) as! SectionHeaderView
            tagsHeader.headerString = "Type"
            tagsHeader.backgroundColor = .blue
            return tagsHeader
        }
    default:
        return UICollectionReusableView()
    }
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
    if section == 0 {
        return CGSize(width: view.frame.width, height: 18 + 22 + 6)
    } else {
        return CGSize(width: view.frame.width, height: 100)
    }
}

Это то, как я создаю экземпляр моего UICollectionView

let searchCollectionView: UICollectionView = {
    let layout = LeftAlignedCollectionViewFlowLayout()
    layout.minimumInteritemSpacing = 6
    layout.minimumLineSpacing = 6
    let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
    cv.isScrollEnabled = false
    cv.register(TokenCell.self, forCellWithReuseIdentifier: "TokenCell")
    cv.register(SectionHeaderView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "TagsHeaderView")
    cv.register(SectionHeaderView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "TypesHeaderView")
    cv.backgroundColor = .white
    cv.showsVerticalScrollIndicator = false
    cv.alwaysBounceVertical = false
    cv.translatesAutoresizingMaskIntoConstraints = false
    return cv
}()

Мой CollectionViewFlowLayout

class LeftAlignedCollectionViewFlowLayout: UICollectionViewFlowLayout {

override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    let attributes = super.layoutAttributesForElements(in: rect)

    var leftMargin = sectionInset.left
    var maxY: CGFloat = -1.0
    attributes?.forEach { layoutAttribute in
        if layoutAttribute.frame.origin.y >= maxY {
            leftMargin = sectionInset.left
        }

        layoutAttribute.frame.origin.x = leftMargin

        leftMargin += layoutAttribute.frame.width + minimumInteritemSpacing
        maxY = max(layoutAttribute.frame.maxY , maxY)
    }

    return attributes
}

}

Вот скриншот текущего результата.Вы можете видеть, что появляется первый заголовок, однако с отступом.Второй заголовок имеет свое место, но ни один из его содержимого не появляется.enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...