【问题标题】:Why can't I get this 2D array to load properly into my custom CollectionViewCells?为什么我不能让这个二维数组正确加载到我的自定义 CollectionViewCells 中?
【发布时间】:2017-07-27 18:24:36
【问题描述】:

在 XCode 中,我正在编写一个程序,其中将 2D 字符串数组中的数据加载到 140 行 x 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() 没用。

【问题讨论】:

    标签: arrays swift multidimensional-array uicollectionview uicollectionviewcell


    【解决方案1】:

    使用 item 和一些简单的算术来代替 row:

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

    }

    【讨论】:

    • 为什么是模3?另外,我尝试让我将 indexPath.item / 3 转换为 Double
    • @Derry,我将它从 3 更改为列数。没有更多的硬编码值:)
    • 现在我在 let columns 行上遇到一个可选错误...这是一个字符串数组数组
    • @Derry。那是因为?。只需将其移至我更新的答案中的 if let 行
    • 现在我得到条件绑定的初始化程序必须具有可选类型,而不是'CGFloat'
    【解决方案2】:

    var 列 = 位置 % MAX_ROWS
    var row = position / MAX_COLUMNS

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-27
      • 1970-01-01
      • 2020-05-11
      • 1970-01-01
      • 2012-10-27
      • 2020-11-19
      • 1970-01-01
      相关资源
      最近更新 更多