jdleung jdleung - 2 years ago 139
Swift Question

How to get cell index around specified cell?

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)
to get other cells' indexPath, but this solution works well but except for those cells outside screen because of collectionView reusing cell.

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
to get index of others, but failed.

Can anyone give any idea to solve this?

Thanks.

Finally get it works with the following code

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
}

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