如何填充一个二维数组到的CollectionView?

问题描述 投票:1回答:2

目前,我有10行和10列的二维数组,我想打印此使用集合视图的前端。但是,我只能得到我的二维数组的集合视图上我的第一行中的数据。我想检索所有行。

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()
}
ios arrays swift uicollectionview
2个回答
0
投票

我设法解决自己的问题。所以一个错误,我认为我所做的是我只返回一行,而不是10因此需要有numberOfSections.So即使结果是能够显示,没有足够的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()
}

-2
投票

尝试这个:

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 = item / numberOfRows+1 //11 in your case
    let column : Int = item % numberOfColumns+1 //11 in your case
    cell.charLabel.text = grid[row][column]
    return cell
}
© www.soinside.com 2019 - 2024. All rights reserved.