ios知识iOS 进阶

给UICollectionView添加头部视图headerVie

2017-03-11  本文已影响5204人  T92

你在使用UITableView时是否用到过tableHeaderView,这个属性让我们设置UITableView的头部视图变得很简单,但是开发中我们有时会用UICollectionView来替代UITableView,然而UICollectionView并没有HeaderView属性,于是很多人并不知道如何设置UICollectionView的头部视图,这里就放上方法。

方式1:通过设置组头的方式进行添加

注:
这种方式实质是设置collectionview组头视图,相当于tableviewfunc tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?方法,因此会影响每组的组头,所以不适用于需要分组且需要单独设置每组组头视图的collectionview

单组效果图 多组效果图

我们要使用CollectionView里面的头视图需要先注册头视图 UICollectionReusableView或者 继承UICollectionReusableView的子类,kind类型为UICollectionElementKindSectionHeader,并且需要带一个标识符。

详细步骤如下:
首先自定义UICollectionView的头部视图,继承自UICollectionReusableView

import UIKit

class CDCollectionHeader: UICollectionReusableView {
    
    let label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 20))
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        backgroundColor = UIColor.red
        addSubview(label)
        label.textColor = UIColor.black
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

添加步骤共3步:

1.设置头部视图size
2.注册头部视图
3.添加header

import UIKit

class ViewController: UIViewController {
    
    fileprivate var collectionView: UICollectionView!
    fileprivate let headerViewId = "headerViewId"
    fileprivate let cellId = "CDCellId"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let layout = UICollectionViewFlowLayout()
        
        //1.设置头部视图size
        layout.headerReferenceSize = CGSize(width: UIScreen.main.bounds.width, height: 100)
        
        collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: layout)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        view.addSubview(collectionView)
        
        //2.注册头部视图
        collectionView.register(CDCollectionHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: headerViewId)
        
        //注册单元格
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellId)
    }
    
}

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
//    func numberOfSections(in collectionView: UICollectionView) -> Int {
//        return 3
//    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 3
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
        cell.backgroundColor = UIColor.yellow
        return cell
    }
    
    //3.添加header
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader{
            let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerViewId, for: indexPath) as! CDCollectionHeader
            header.label.text = "我是header"
            return header
        }
        return UICollectionReusableView()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 150)
    }
    
}

好了,这样头部视图就添加成功了。

方式二:通过contentInset设置

2019.01.18更新:
如评论3楼所述,上述方式(方式一)确实是会影响组头的,如果分了多组数据,就会每组都带这个header,这时只需要设置第一组显示,其他组不显示即可,不过存在一个问题是每组都需要设置自身的header时,上述方法不再适用。评论提及设置contentInset达到设置header且不影响组头的方式,我试了下,确实比较好使,感谢成长路上各位同仁的技术分享。
代码:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let layout = UICollectionViewFlowLayout()
        
        let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height), collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = UIColor.white
        collectionView.showsVerticalScrollIndicator = false
        view.addSubview(collectionView)
        
        collectionView.contentInset = UIEdgeInsets(top: 300, left: 0, bottom: 0, right: 0)

        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellId")
        
        let head = UIView(frame: CGRect(x: 0, y: -300, width: collectionView.frame.width, height: 300))
        collectionView.addSubview(head)
        head.isUserInteractionEnabled = true
        head.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tap)))
        head.backgroundColor = UIColor.red
    }
    
    @objc func tap(){
        print("tap")
    }

}

extension ViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath)
        cell.backgroundColor = UIColor.yellow
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 100, height: 150)
    }
}
效果图
上一篇下一篇

猜你喜欢

热点阅读