使用网格(UICollectionView)进行流布局

import UIKit

class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {

    var nameArr:[String]?
    var picArr :[String]?
    
    var collect : UICollectionView?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        picArr = ["1","2","3","4","5","6"]
        nameArr = ["一","二","三","四","五","六"]
        collect = UICollectionView(frame: self.view.frame, collectionViewLayout: UICollectionViewFlowLayout())
        collect?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cellID")
        collect?.delegate = self
        collect?.dataSource = self
        self.view.addSubview(collect!)
        // Do any additional setup after loading the view, typically from a nib.
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return (picArr?.count)!
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellID", for: indexPath)
        let img = UIImageView(frame: CGRect(x: 0, y: 0, width: 60, height: 60))
        img.image = UIImage(named: (picArr?[indexPath.item])!)
        cell.contentView.addSubview(img)
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("\(nameArr?[indexPath.item])")
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容