0

I have an array that I'm using to create a grid with the use of a collection view. To provide the numberOfItemsInSection in the collectionView I am doing row.count * row.count to get an 8x8 grid and 64 cells. My problem is that I want to be able to access and manipulate these cells via their rows and columns, not the indexPath.row.

So if I want the 5th cell, instead of getting #4 in IndexPath.row I want to be able to do: row[0][4]. Any suggestions on how to convert IndexPath.row into a 2D array?

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

ielyamani
  • 17,807
  • 10
  • 55
  • 90
JohnO
  • 17
  • 4

2 Answers2

0

The following should do it.

row[indexPath.row / 8][indexPath.row % 8]
Craig Siemens
  • 12,942
  • 1
  • 34
  • 51
0

Why not simply 8 sections with 8 rows, that's what IndexPath is designed for

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

vadian
  • 274,689
  • 30
  • 353
  • 361