首页 > 解决方案 > 标题中的不同标签取决于集合视图中的部分

问题描述

 let titles = ["Popularity","Top Rated","Release Date","Revenue"]

func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
    let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: Header.identifier, for: indexPath) as! Header 
    header.label.text = titles[indexPath.section]
    return header
}

我想做的标题文本会根据每个部分中的标题数组而有所不同。我可以看到标题中的空白,但其中没有标题。

这是我的 Header 类:

class Header: UICollectionReusableView {
static let identifier = "Header"

let label = UILabel()

override init(frame: CGRect) {
    super.init(frame: frame)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

override func layoutSubviews() {
    super.layoutSubviews()
    label.frame = bounds
}
}

同样在 viewDidLoad() 中,我写了这个。

collectionV.register(Header.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: Header.identifier)

我错过了什么?

标签: swiftuicollectionview

解决方案


推荐阅读