ios - 如何将二维数组填充到 CollectionView 上?

标签 ios arrays swift uicollectionview

目前,我有一个 10 行 10 列的二维数组,我想使用 Collection View 将其打印到前端。但是,我只能将二维数组中第一行的数据获取到 Collection View 。我想检索所有行。

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? WordSearchTableViewCell, let columns = grid.first?.count{
    //print(columns)
    let item = CGFloat(indexPath.item)
    //print("item: ", item)
    let row = floor(item / CGFloat(columns))
    //print("row: " , row)

    let column = item.truncatingRemainder(dividingBy: CGFloat(columns))
    print("column: ",column)

    //setCharacter
    cell.charLabel.text = grid[Int(row)][Int(column)]
    return cell
    }
    print("error")
    return WordSearchTableViewCell()
}

最佳答案

我设法解决了我自己的问题。所以我认为我犯的一个错误是我只返回一行而不是 10 行,因此需要有 numberOfSections。所以即使结果能够显示,也没有足够的 collectionviewCell。

对于循环过程,我设置了一个计数器来跟踪行号,每当该列到达该行数组的最后一个元素时,就会有一个增量。

不确定我的解释是否正确。

var counter: Int = 0

func numberOfSections(in collectionView: UICollectionView) -> Int {
    //return columns
    return grid.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //return rows
    return grid[section].count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as? WordSearchTableViewCell, let columns = grid.first?.count{

        let item = indexPath.item
        let row : Int = counter
        let column : Int = Int(CGFloat(item).truncatingRemainder(dividingBy: CGFloat(columns)))

        //rowNum + 1 each time reaches last item of column
        if column == 9 {
            counter = counter + 1
        }

    //setCharacter
    cell.charLabel.text = grid[row][column]
    return cell
    }

    print("error")
    return UICollectionViewCell()
}

关于ios - 如何将二维数组填充到 CollectionView 上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556237/

相关文章:

ios - 如何在 iOS 模拟器中单击主页按钮?

ios - 媒体未在 iOS phonegap 1.5 应用程序中播放

python - 从列表和其他单个值创建 numpy 数组的最佳方法

ios - 如何在 View Controller 的多个 View 中添加多种渐变颜色

ios - Swift +隐藏或删除 UIView

ios - Xcode中用于Unity Demo的Google Cardboard SDK的构建错误

ios - 使用lua io.open在iOS上拒绝权限

JavaScript Array join() 导致结果中出现空 (%00) 字符

python - 稀疏数据的 3D 数组与稀疏矩阵

ios - 如何在 Swift 中关联两个数组