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

时间:2017-07-27 18:24:36

标签: arrays swift multidimensional-array uicollectionview uicollectionviewcell

在XCode中,我正在编写一个程序,其中来自2D String数组的数据被加载到140行×5列表中。有了这个示例,如果我的数组是{{a,b,c} {d,e,f}},我想要一个像

这样的表
a  b  c
d  e  f

但是我继续得到什么a,d作为我的表的前2个元素在第一行正确。我的代码是:

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(),但它没有用。

2 个答案:

答案 0 :(得分:3)

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

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()

}

答案 1 :(得分:0)

var column = position%MAX_ROWS
var row = position / MAX_COLUMNS

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

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