Ank*_*arg 54
要在UICollectionView的每个部分上方添加自定义标签,请按照以下步骤操作
将节头中的标签连接到UICollectionReusableView文件
class SectionHeader: UICollectionReusableView {
@IBOutlet weak var sectionHeaderlabel: UILabel!
}
Run Code Online (Sandbox Code Playgroud)在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()
}
Run Code Online (Sandbox Code Playgroud)这里"SectionHeader"是添加到UICollectionReusableView类型的文件的名称
mat*_*att 37
实现collectionView:viewForSupplementaryElementOfKind:atIndexPath:
并提供包含标签的出列UICollectionElementKindSectionHeader.如果这是一个流程布局,请务必设置headerReferenceSize
或仍然看不到任何内容.
Eve*_*ibe 20
如果您想要 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")
}
}
Run Code Online (Sandbox Code Playgroud)
使用自定义视图实现 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()
}
}
Run Code Online (Sandbox Code Playgroud)
实现 referenceSizeForHeaderInSection 和 referenceSizeForFooterInSection 方法。标题方法如下所示:
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.frame.width, height: 40)
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
31545 次 |
最近记录: |