将IndexPath.row转换为2D数组

时间:2019-03-17 18:35:42

标签: arrays swift uicollectionview uicollectionviewcell

我有一个数组,正在使用集合视图创建一个网格。为了在collectionView中提供numberOfItemsInSection,我正在做row.count * row.count以获取8x8网格和64个单元格。我的问题是我希望能够通过它们的行和列而不是indexPath.row来访问和操纵这些单元格。

因此,如果我想要第5个单元格,而不是在IndexPath.row中获得#4,我希望能够做到:row [0] [4]。关于如何将IndexPath.row转换为2D数组的任何建议?

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

2 个答案:

答案 0 :(得分:0)

以下应该这样做。

row[indexPath.row / 8][indexPath.row % 8]

答案 1 :(得分:0)

为什么不简单地用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
}

enter image description here