UICollectionView start operation

1. Basic operations

1.0 Initialize the UICollectionView

/ / lazy loading
lazy var collectView: UICollectionView = {
   			// FlowLayout custom Settings
        let layout = UICollectionViewFlowLayout.init(a)// Set item alignment (horizontal, vertical)
  			layout.scrollDirection = .vertical
 				// Set the size of item
        layout.itemSize = CGSize(width: self.view.frame.size.width/4, height: self.view.frame.size.width/4)
  			/ / column spacing
        layout.minimumLineSpacing = 1
  			/ / line spacing
        layout.minimumInteritemSpacing = 1
        // Set the margin of item
        layout.sectionInset =UIEdgeInsetsMake(10.0.10.0)
        // Set the page header size
        layout.footerReferenceSize = CGSize(width: self.view.frame.size.width, height: 50)
  			// Set the footer size
        layout.headerReferenceSize = CGSize(width: self.view.frame.size.width, height: 50)
        / / initialization
  			let collectview = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
  			// Set the background color
        collectview.backgroundColor = .green
        // Set the proxy object
        collectview.delegate = self
        // Set the data source object
        collectview.dataSource = self
        collectview.showsVerticalScrollIndicator = true
  			// Sets the vertical scroll to the bottom of the item
  			collectview.alwaysBounceVertical = true
  			// Sets the horizontal scroll to the right of the item
        collectview.alwaysBounceHorizontal = true
  			// Enable paging in uicollectionView
        collectview.isPagingEnabled = true
        / / register Cell
        collectview.register(ProfessTypeViewCell.self, forCellWithReuseIdentifier: "ProfessTypeViewCell")

        / / register Hearder
  			collectview.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "reusable")
        return collectview
 }()
Copy the code

1.1 UICollectionViewDelegate

extension LZCollectionVC : UICollectionViewDelegate{
     // MARK: -item click
    func collectionView(_ collectionView: UICollectionView.didSelectItemAt indexPath: IndexPath) {
        print("Response to click events")}}Copy the code

1.2 UICollectionViewDataSource

extension LZCollectionVC : UICollectionViewDataSource{
    // Set the number of groups
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 6
    }
    // Set the format of each item group
    func collectionView(_ collectionView: UICollectionView.numberOfItemsInSection section: Int) -> Int {
        return 9
    }
    / / register cell
    func collectionView(_ collectionView: UICollectionView.cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellString = "ProfessTypeViewCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellString, for: indexPath)
        cell.backgroundColor = .red
        return cell
    }
}
Copy the code

1.3 UICollectionViewDelegateFlowLayout

extension ViewController : UICollectionViewDelegateFlowLayout{
    // MARK: - item Size
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width / 3.73
        return CGSize(width: width, height: width + 20)}// MARK: - Border distance
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)}// MARK: - Minimum line spacing
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }
    // MARK: - Minimum column spacing
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 20}}Copy the code

1.4 Header and Footer Settings

// MARK: - Set header and footer methods according to kind
    func collectionView(_ collectionView: UICollectionView.viewForSupplementaryElementOfKind kind: String.at indexPath: IndexPath) -> UICollectionReusableView {
        if kind = = UICollectionView.elementKindSectionHeader{
            let headerV = collectionView .dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerIdentifier", for: indexPath)
            headerV.backgroundColor = armColor()
            return headerV
        }else if kind = = UICollectionView.elementKindSectionFooter{
            let footerV = collectionView .dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footIdentifier", for: indexPath)
            footerV.backgroundColor = armColor()
            return footerV
        }
        return UICollectionReusableView.init()}// MARK: -headerView high
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize (width: screenW, height: 100)}// MARK: -footerView height
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize (width: screenW, height: 100)}Copy the code

1.5 Item highlighting

  // MARK: - Whether to highlight
    func collectionView(_ collectionView: UICollectionView.shouldHighlightItemAt indexPath: IndexPath) -> Bool{
        return true
    }
    
    // MARK: - Highlight colors
    func collectionView(_ collectionView: UICollectionView.didHighlightItemAt indexPath: IndexPath){
        let cell = collectionView .cellForItem(at: indexPath)
        cell?.backgroundColor = armColor()
    }
    
    // MARK: - Cancel the long press on color
    func collectionView(_ collectionView: UICollectionView.didUnhighlightItemAt indexPath: IndexPath){
        let cell = collectionView .cellForItem(at: indexPath)
        cell?.backgroundColor = kColor(red: 53, green: 49, blue: 59)}func armColor(a)->UIColor{
        let red = CGFloat(arc4random()%256)/255.0
        let green = CGFloat(arc4random()%256)/255.0
        let blue = CGFloat(arc4random()%256)/255.0
        print("red:\(red),green:\(green),blue:\(blue)")
        return UIColor(red: red, green: green, blue: blue, alpha: 1.0)}Copy the code

Remark:

The agency agreement is realized by using the way of viewcontrollers separate function way: “the extension LZCollectionVC: UICollectionViewDataSource”.

Overall description:

import UIKit

class LZCollectionVC: UIViewController{
    
  
    lazy var hearderImage:UIImageView = {
        let hearderImage = UIImageView()
        hearderImage.image = UIImage(named: "doctor")
        return hearderImage
    }()

    
    lazy var collectView: UICollectionView = {
        let layout = UICollectionViewFlowLayout.init(a)// Set the size of item
        layout.itemSize = CGSize(width: self.view.frame.size.width/4, height: self.view.frame.size.width/4)
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        layout.scrollDirection = .vertical
        //
        layout.footerReferenceSize = CGSize(width: self.view.frame.size.width, height: 50)
        layout.headerReferenceSize = CGSize(width: self.view.frame.size.width, height: 50)
        let collectview = UICollectionView.init(frame: self.view.bounds, collectionViewLayout: layout)
        collectview.backgroundColor = .green
        collectview.delegate = self
        collectview.dataSource = self
        collectview.showsVerticalScrollIndicator = true
        collectview.isPagingEnabled = true
        / / register Cell
        collectview.register(ProfessTypeViewCell.self, forCellWithReuseIdentifier: "ProfessTypeViewCell")

        //
// collectview.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "reusable")
        return collectview
    }()
    
    override func viewDidLoad(a) {
        super.viewDidLoad()
        self.creatUI()
    }
    
    func creatUI(a) -> Void {
        self.view.addSubview(self.collectView)
        self.collectView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))}}}extension LZCollectionVC : UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView.didSelectItemAt indexPath: IndexPath) {
        print("Response to click events")}}extension LZCollectionVC : UICollectionViewDataSource{
    // Set the number of groups
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 6
    }
    // Set the format of each item group
    func collectionView(_ collectionView: UICollectionView.numberOfItemsInSection section: Int) -> Int {
        return 9
    }
    / / register cell
    func collectionView(_ collectionView: UICollectionView.cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cellString = "ProfessTypeViewCell"
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellString, for: indexPath)
        cell.backgroundColor = .red
        return cell
    }
}

extension ViewController : UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.sizeForItemAt indexPath: IndexPath) -> CGSize {
        let width = collectionView.frame.width / 3.73
        return CGSize(width: width, height: width + 20)}func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)}func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 20
    }
    func collectionView(_ collectionView: UICollectionView.layout collectionViewLayout: UICollectionViewLayout.minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 20}}Copy the code

2. UICollectionViewCell User-defined

### 1. Basic examplesCopy the code
import Foundation
class ProfessTypeViewCell: UICollectionViewCell {
    
    lazy var mTextLabel: UILabel = {
        let mTextLabel = UILabel()
        mTextLabel.font = UIFont.systemFont(ofSize: 14)
        mTextLabel.textAlignment = NSTextAlignment.center
        mTextLabel.layer.masksToBounds = true
        mTextLabel.layer.cornerRadius = 18
        mTextLabel.text = "Item"
        return mTextLabel
    }()
    
    lazy var mImage: UIImageView = {
        let mImage = UIImageView()
        mImage.image = UIImage(named: "gridman")
        return mImage
    }()
    
    override init(frame:CGRect) {
        
        super.init(frame: frame)
        
        let cellWidth:CGFloat = self.frame.size.width
        let cellHeight:CGFloat = self.frame.size.height
        
        self.contentView.addSubview(self.mImage)
        
        self.mImage.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.centerY.equalTo(self).offset(-10)
            make.width.equalTo(cellWidth/3)
            make.height.equalTo(cellHeight/3)}self.contentView.addSubview(self.mTextLabel)
        
        self.mTextLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self.mImage.snp.bottom).offset(10)
            make.width.equalTo(cellWidth)
            make.height.equalTo(20)}}required init?(coder: NSCoder) {
        fatalError("init(coder:)has not been implemented")}}Copy the code