简体   繁体   中英

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
    }

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
}

Think about it logically.

To get the "bordering" cells based on a cell index in an array of rows and columns, you need to:

  1. get the cell directly above it, and get the cells to the left and right of that cell
  2. get the cells to the left and right of the specified cell
  3. get the cell directly below it, and get the cells to the left and right of that cell

For bounds handling:

  • don't try to get cells above if the cell is on the top row, and don't try to get cells below if the cell is on the bottom row
  • don't try to get cells to the left if the cell is in the first column, and don't try to get cells to the right if the cell is in the last column

As you work that out in code, keep in mind the index is Zero-based... so in your 3x3 example, your indexes are 0 thru 8, not 1 thru 9.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM