当前,我有一个10行10列的2D数组,我想使用Collection View将其打印到前端。但是,我只能将2D数组中第一行的数据获取到集合视图。我想检索所有行。
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()
}
答案 0 :(得分:0)
我设法解决了自己的问题。所以我想我做的一个错误是我只返回一行而不是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()
}
答案 1 :(得分:-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
}