使用網格(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.
    }


}

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容