为什么我不能让这个 2D 数组正确加载到我的自定义 CollectionViewCells 中?

Why can't I get this 2D array to load properly into my custom CollectionViewCells?

在 XCode 中,我正在编写一个程序,其中将二维字符串数组中的数据加载到 140 行乘 5 列 table 中。对于这个示例,如果我的数组是 {{a,b,c}{d,e,f}},我想要一个 table like

a  b  c
d  e  f

但我一直在第一行得到 table 的前两个元素 a、d。我的代码是:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> GridViewCell {
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath as IndexPath) as? GridViewCell{

        var i = 0

        while (i < 5){
        cell.textLabel?.text = wholeArray[indexPath.row][i]

        cell.backgroundColor = UIColor.gray
        return cell
        }

    }
    else {
        DLog("ERROR")
        return GridViewCell()
    }
}

如果有 indexPath.column,我会尝试,但没有。我怎样才能让它做我需要的?这是一个字符串数组;我试过 flatten() 但没用。

使用带有一些简单算术的项目代替行:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> GridViewCell {    
    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "gridCell", for: indexPath as IndexPath) as? GridViewCell, let columns = wholeArray.first?.count {
        let item = CGFloat(indexPath.item)

        let row = floor(item / CGFloat(columns))
        let column = item.truncatingRemainder(dividingBy: CGFloat(columns))

        cell.textLabel?.text = wholeArray[Int(row)][Int(column)]

        return cell
    } // no need to explicitly say else

    print("error")
    return GridViewCell()

}

var 列 = 位置 % MAX_ROWS
var 行 = 位置 / MAX_COLUMNS

这应该会降低您的位置(索引),并为您提供可用于索引到二维数组中的列和行,以便获得您正在寻找的结果。

您的基本问题是网格被视为单元格的线性列表,您只需要一些简单的数学运算即可转换为二维网格。