iOS swift UICollectionView的基本使用

苹果官方demo(oc版):用的是UICollectionViewController,不一定很适用
官方文档

//
//  collectionViewVC.swift
//  十六进制键盘
//
//  Created by macvivi on 2021/1/8.
//

import UIKit

class CollectionViewVC: UIViewController {
    
    @IBOutlet var collectionView: UICollectionView!
    
    let content = "0123456789abcdef"

    override func viewDidLoad() {
        super.viewDidLoad()
        title = "编辑(collectionView)"
        setupUI()
        collectionView.isHidden = true
    }
    
    override func viewDidAppear(_ animated: Bool) {
        collectionView.isHidden = false
        collectionView.collectionViewLayout = layout
    }
    
    func setupUI() {
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    

    lazy var layout: UICollectionViewFlowLayout = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 1
        layout.minimumInteritemSpacing = 1
        layout.sectionInset = UIEdgeInsets(top: 2, left: 2, bottom: 2, right: 2)
        layout.itemSize = CGSize(width: collectionView.width/4.1, height: collectionView.height/4.1)
        
        return layout
    }()
}

extension CollectionViewVC: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return content.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell: ContentCell = collectionView.dequeueReusableCell(withReuseIdentifier: "ContentCell", for: indexPath) as! ContentCell
        let index = content.index(content.startIndex, offsetBy: indexPath.row)
        cell.contentLabel.text = String(content[index...index])
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell: ContentCell = collectionView.cellForItem(at: indexPath)! as! ContentCell

    }
    
}

class ContentCell: UICollectionViewCell {
    
    @IBOutlet var contentLabel: UILabel!
    
}

在这里插入图片描述
在这里插入图片描述

参考博客:
UICollectionView的基本使用
商城类商品展示瀑布流(swift) - cocoaChina

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页