Swift collectionView 基础使用篇

1061646448596_.pic.jpg

当我们拿到像这样的设计图,我们就可以用collectionView来轻松实现

遵守collectionView的协议

class AncientBookClassVC: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

懒加载创建collectionView

private let AncientBookCellID = "AncientBooksRightCell"
   private let AncientBookHeadID = "AncientBookClassHead"
    
    lazy var classCollectView : UICollectionView = {
     //设置布局
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout.init() 
        let itemSpac = (kScreenWidth - 60 - 14 - (59*4)) / 3
        layout.scrollDirection = .vertical //竖直
        layout.itemSize = CGSize.init(width: 59, height: 142)
        layout.minimumInteritemSpacing = itemSpac //item 间距
        layout.minimumLineSpacing = 5
        layout.sectionInset = .init(top: 5, left: 30, bottom: 0, right: 30)

        let collectView = UICollectionView.init(frame: .zero, collectionViewLayout: layout)
        collectView.delegate = self
        collectView.dataSource = self
        collectView.backgroundColor = .white.withAlphaComponent(0)
        collectView.showsVerticalScrollIndicator = false
        
//注册cell、 header、 Footer
        collectView.register(AncientBooksRightCell.self, forCellWithReuseIdentifier: AncientBookCellID)
        collectView.register(AncientBookClassHead.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: AncientBookHeadID)
        collectView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "foot")
      
        layerView.addSubview(collectView)
        return collectView
    }()

必须实现的两个代理

  1. 设置每组显示的item 数量
 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
  1. 设置UICollectionViewCell
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AncientBookCellID, for: indexPath) as! AncientBooksRightCell
        
        let model = dataArray[indexPath.row]
        
        cell.titleLab.text = model?.name
        cell.subTitleLab.text = model?.content
        
        return cell
    }

其他常用代理简介

  • 点击item响应
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

}
  • 设置组的数量(默认 1组)
 func numberOfSections(in collectionView: UICollectionView) -> Int {
      return 1
    }
  • 设置组header size
  func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize.init(width: kScreenWidth-14, height: 84)
    }
  • 设置组Footer size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize.init(width: kScreenWidth, height: 0.001)
    }
  • 设置组headerView & FooterView
 func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        if kind == UICollectionView.elementKindSectionHeader {
            let head = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: AncientBookHeadID, for: indexPath) as! AncientBookClassHead
            return head
        }else{
            let footerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "foot", for: indexPath)
            return footerView
        }
    }

自定义 UICollectionViewCell

import UIKit

class AncientBooksRightCell: UICollectionViewCell {
    
    lazy var topLineView: UIView = {
        let line = UIView()
        line.backgroundColor = UIColor.init(hexString: "#E5DFCF")
        contentView.addSubview(line)
        return line
    }()
    
    lazy var titleLab: UILabel = {
        let lab = UILabel()
        lab.text = "易类"
        lab.textColor = UIColor.init(hexString: "#060606")
        lab.font = UIFont.systemFont(ofSize: 21)
        lab.textAlignment = .center
        lab.numberOfLines = 0
        contentView.addSubview(lab)
        return lab
    }()
    
    
    lazy var subTitleLab: UILabel = {
        let lab = UILabel()
        lab.text = "昔在帝尧"
        lab.textColor = UIColor.init(hexString: "#7D7A76")
        lab.font = UIFont.systemFont(ofSize: 13)
        lab.textAlignment = .center
        lab.numberOfLines = 0
        contentView.addSubview(lab)
        return lab
    }()
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    func initUI()
    {
        topLineView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(2)
        }
        titleLab.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(7)
            make.top.equalTo(topLineView.snp.bottom).offset(14)
            make.width.equalTo(19)
            make.bottom.lessThanOrEqualToSuperview()
        }
        
        subTitleLab.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-11)
            make.top.equalTo(titleLab.snp.top)
            make.width.equalTo(12)
        }
        
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

自定义Header

import UIKit

class AncientBookClassHead: UICollectionReusableView {
    
    lazy var gridView: TitleGridView = {
        let grid = TitleGridView.init(frame: .zero)
        self.addSubview(grid)
        return grid
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        gridView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(19)
            make.left.right.equalToSuperview()
        }
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

注意! Header 和 Footer 出现一定是配对的,像这样的需要看着只需要实现header,但是也得加个隐藏的Footer,不知道原因,只是经验之谈

你可能感兴趣的:(Swift collectionView 基础使用篇)