collectionView:viewForSupplementaryElementOfKind:atIndexPath:仅使用UICollectionElementKindSectionHeader调用

Ste*_*ncu 15 ios ios6

我有一个集合视图,我希望每个部分都有一个页眉和一个页脚.我正在使用默认的流布局.

我有自己的子类,UICollectionReusableView并在viewDidLoad视图控制器的方法中为页眉和页脚注册每个子类.

我已经实现了方法collectionView:viewForSupplementaryElementOfKind:atIndexPath:,但是,对于每一个部分,它只是调用kindUICollectionElementKindSectionHeader.因此我的页脚甚至没有创建.

任何想法为什么会这样?

Ste*_*ncu 11

看来我必须设置footerReferenceSize集合视图布局.奇怪的是,我不需要用标题来做那件事.

  • 我有相同的经验(页眉和页脚) - 似乎如果你没有设置这些,它不会尝试加载页眉和页脚.老实说,感觉API缺少像" - (BOOL)indexPath:hasSupplementalViewOfKind:"这样的方法,让开发人员明确确定哪些indexPath具有补充视图. (3认同)

Daw*_*ong 8

(使用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.