【发布时间】:2015-07-12 09:01:23
【问题描述】:
我需要在我的收藏视图中的每个部分上方添加一个标签。我尝试简单地将标签拖到原型单元格上方的标题空间中,但每次运行应用程序时,标签都不可见。
有什么帮助吗?
【问题讨论】:
我需要在我的收藏视图中的每个部分上方添加一个标签。我尝试简单地将标签拖到原型单元格上方的标题空间中,但每次运行应用程序时,标签都不可见。
有什么帮助吗?
【问题讨论】:
如果您想要 Swift 4.2 中的编程解决方案,您可以执行以下操作:
设置 UICollectionViewDelegate 和 UICollectionViewDelegateFlowLayout
使用您想要定义的任何视图创建自定义 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")
}
}
使用自定义视图实现 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()
}
}
实现referenceSizeForHeaderInSection 和referenceSizeForFooterInSection 方法。例如下图的Header方法:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 40)
}
【讨论】:
self.collectionView.register(SectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "header")
要在 UICollectionView 的每个部分上方添加自定义标签,请按照以下步骤操作
将节标题中的标签连接到 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 类型的文件的名称
【讨论】:
实现 collectionView:viewForSupplementaryElementOfKind:atIndexPath: 并提供一个包含您的标签的出列 UICollectionElementKindSectionHeader。如果这是一个流式布局,请务必同时设置headerReferenceSize,否则您仍然看不到任何内容。