将2D数组填充到CollectionView上可以通过以下步骤实现:
以下是一个示例代码,演示如何将2D数组填充到CollectionView上:
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var collectionView: UICollectionView!
var data: [[Int]] = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] // 示例2D数组数据
override func viewDidLoad() {
super.viewDidLoad()
// 创建CollectionView并设置布局
let layout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
view.addSubview(collectionView)
}
// 返回2D数组的行数
func numberOfSections(in collectionView: UICollectionView) -> Int {
return data.count
}
// 返回指定行的列数
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return data[section].count
}
// 填充数据到单元格
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)
let value = data[indexPath.section][indexPath.item]
cell.backgroundColor = UIColor.gray
cell.textLabel?.text = "\(value)"
return cell
}
// 自定义单元格大小
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.bounds.width / CGFloat(data[indexPath.section].count)
return CGSize(width: width, height: width)
}
}
这个示例代码中,我们创建了一个CollectionView,并将2D数组的数据填充到单元格中。你可以根据实际需求自定义单元格的样式和布局。
领取专属 10元无门槛券
手把手带您无忧上云