jdleung - 1 year ago 128

Swift Question

In CollectionView, I want to get all cells' indexPath.row around the pressed cell .

I had tried to get the pressed cell's position, and then use

`collectionView.indexPathForItem(at: CGPoint)`

Now I'm trying to get them by indexPath only, assume collectionView has 3 rows and 3 cols:

1 2 3

4 5 6

7 8 9

Press each of numbers and get all other index around it: top, left, right, bottom, top left, top right, bottom left, bottom right. If a number has no all position, ignore it. For example, number 1 has no left, top, top left and bottom left.

`let cellsPerRow = 3`

let t = pressedCell.index - 3

if t >= 0{

top = t

}

let b = pressedCell + 3

if b <= 9{

bottom = b

}

The above code can only get index of top and bottom, I also tried to use

`pressedCell.index%cellsPerRow`

Can anyone give any idea to solve this?

Thanks.

`var indexArroundDict = [String:Int]()`

let top = index - cellsPerRow

if top >= 0 {

indexArroundDict["top"] = index - cellsPerRow

}

let b = index + cellsPerRow

if b < totalCellArr.count {

indexArroundDict["bottom"] = b

}

if index%cellsPerRow != 0 {

indexArroundDict["left"] = index - 1

}

if index%cellsPerRow != cellsPerRow-1 {

indexArroundDict["right"] = index + 1

}

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

This should do the trick:

```
let cellsPerRow = 3
let numberOfRows = 3
let index = pressedCell.index
if index > cellsPerRow {
top = index - cellsPerRow
}
if index < (numberOfRows - cellsPerRow) {
bottom = b
}
if index%cellsPerRow != 1 {
left = index -1
}
if index%cellsPerRow != 0 {
right = index + 1
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**