我有一个集合视图,我希望每个部分都有一个页眉和一个页脚.我正在使用默认的流布局.
我有自己的子类,UICollectionReusableView并在viewDidLoad视图控制器的方法中为页眉和页脚注册每个子类.
我已经实现了方法collectionView:viewForSupplementaryElementOfKind:atIndexPath:,但是,对于每一个部分,它只是调用kind是UICollectionElementKindSectionHeader.因此我的页脚甚至没有创建.
任何想法为什么会这样?
Ste*_*ncu 11
看来我必须设置footerReferenceSize集合视图布局.奇怪的是,我不需要用标题来做那件事.
(使用Swift 3.1,Xcode 8.3.3)
首先,注册头部的类或nib
collectionView.register(ShortVideoListHeader.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header")
Run Code Online (Sandbox Code Playgroud)
第二,设定headerReferenceSize; 或者,您可以headerReferenceSize在collectionView的委托中返回
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
(collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.headerReferenceSize = CGSize(width: view.bounds.width, height: 156)
}
Run Code Online (Sandbox Code Playgroud)
第三,编写自己的头类,例如,
class ShortVideoListHeader: UICollectionReusableView {
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(titleLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
titleLabel.sizeToFit()
titleLabel.frame.origin = CGPoint(x: 15, y: 64 + (frame.height - 64 - titleLabel.frame.height) / 2) // navigationBar's height is 64
}
}
Run Code Online (Sandbox Code Playgroud)
第四,在collectionView的dataSource方法中返回头部实例,
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "header", for: indexPath) as! ShortVideoListHeader
header.titleLabel.text = title
header.setNeedsLayout()
return header
default:
return UICollectionReusableView()
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,Apple的文档回答了如何隐藏节标题.
此方法必须始终返回有效的视图对象.如果您不希望在特定情况下使用补充视图,则布局对象不应为该视图创建属性.或者,也可以通过设置相应的属性为YES的隐藏属性隐藏视图或属性的alpha属性设置为0.要隐藏在流布局页眉和页脚的观点,还可以设置的那些视图的宽度和高度到0.
| 归档时间: |
|
| 查看次数: |
21920 次 |
| 最近记录: |