我有一个数组,用于通过 Collection View 创建网格。为了在 collectionView 中提供 numberOfItemsInSection,我正在执行 row.count * row.count
来获取 8x8 网格和 64 个单元格。我的问题是我希望能够通过行和列而不是indexPath.row 访问和操作这些单元格。
因此,如果我想要第 5 个单元格,而不是在 IndexPath.row 中获取 #4,我希望能够执行以下操作:row[0][4]。关于如何将 IndexPath.row 转换为二维数组有什么建议吗?
var row = [[Int]]()
let column: [Int]
init() {
self.column = [1, 2, 3, 4, 5, 6, 7, 8]
}
func createGrid() {
for _ in 1...8 {
row.append(column)
}
}
the blue squares/cells are the cells that I want the row and columns for
最佳答案
为什么不简单地使用 8 个部分和 8 行,这就是 IndexPath
的设计目的
var grid = [[Int]]()
override func viewDidLoad() {
super.viewDidLoad()
for _ in 0..<8 {
grid.append([0,1,2,3,4,5,6,7])
}
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return grid.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return grid[section].count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.label.text = "\(indexPath.section)/\(indexPath.row)"
return cell
}
关于arrays - 将 IndexPath.row 转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55210544/