Swift collectionView 基礎使用篇

1061646448596_.pic.jpg

當我們拿到像這樣的設計圖,我們就可以用collectionView來輕松實現(xiàn)

遵守collectionView的協(xié)議

class AncientBookClassVC: BaseViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout

懶加載創(chuàng)建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
    }()

必須實現(xiàn)的兩個代理

  1. 設置每組顯示的item 數(shù)量
 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) {

}
  • 設置組的數(shù)量(默認 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 出現(xiàn)一定是配對的,像這樣的需要看著只需要實現(xiàn)header,但是也得加個隱藏的Footer,不知道原因,只是經(jīng)驗之談??

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容