我想知道如何在UICollectionView
中找到水平和垂直相邻或周围的单元格/ IndexPaths到特定(红色)单元格。
红细胞可能处于任何位置。
我可以找到红色单元格indexPath
,它位于任何位置。
任何帮助或想法将不胜感激。
答案 0 :(得分:1)
假设:
每行有四个单元格。
计算:
int rowCount = 4
//连续的单元格总数。正如你已经描述的那样。int lastRow = totalCell / rowCount
//最后一行。int colNo = index % rowCount
//列号,即此索引位于哪一列int rowNo = index / rowCount
//此索引位于哪一行<强> ALGO 强>
1. if `colNo == 0` // cell is the left most.
if `rowNo == 0` // index of first row
adjacent = index + 1, index + rowCount
else if `rowNo == lastRow` // index of last row
adjacent = index + 1, index - rowCount
else
adjacent = index + 1, index - rowCount
2. if `colNo == 1` // cell is the second in its row .
if `rowNo == 0` // index is at first row
adjacent = index - 1, index + 1, index + rowCount
else if `rowNo == lastRow` // index is at last row
adjacent = index - 1 ,index + 1, index - rowCount
else
adjacent = index + 1, index - rowCount, index - 1
3. if `colNo == 2` // cell is the third in row.
if `rowNo == 0` // index of first row
adjacent = index - 1, index + 1, index + rowCount
else if `rowNo == lastRow` // index of last row
adjacent = index - 1, index + 1, index - rowCount
else
adjacent = index + 1, index - rowCount, index - 1
4. if `colNo == 3` // cell is the left most.
if `rowNo == 0` // index of first row
adjacent = index - 1, index + rowCount
else if `rowNo == lastRow` // index of last row
adjacent = index - 1, index - rowCount
else
adjacent = index - 1, index - rowCount
答案 1 :(得分:0)
我的解决方案不考虑任何间距或不同的单元格大小,但是为了让您了解它是如何工作的:
private func selectCellAndAdjacentCellsAtIndexPath(_ indexPath: IndexPath) {
if let cell = collectionView?.cellForItem(at: indexPath) {
var cellsToSelect: [UICollectionViewCell] = [cell]
// get adjacent cells
// top
if let topIndexPath = collectionView?.indexPathForItem(at: CGPoint(x: cell.center.x, y: cell.center.y - cell.frame.height)), let topCell = collectionView?.cellForItem(at: topIndexPath) {
cellsToSelect.append(topCell)
}
// left
if let leftIndexPath = collectionView?.indexPathForItem(at: CGPoint(x: cell.center.x - cell.frame.width, y: cell.center.y)), let leftCell = collectionView?.cellForItem(at: leftIndexPath) {
cellsToSelect.append(leftCell)
}
// bottom
if let bottomIndexPath = collectionView?.indexPathForItem(at: CGPoint(x: cell.center.x, y: cell.center.y + cell.frame.height)), let bottomCell = collectionView?.cellForItem(at: bottomIndexPath) {
cellsToSelect.append(bottomCell)
}
// right
if let rightIndexPath = collectionView?.indexPathForItem(at: CGPoint(x: cell.center.x + cell.frame.width, y: cell.center.y)), let rightCell = collectionView?.cellForItem(at: rightIndexPath) {
cellsToSelect.append(rightCell)
}
// select cells
for cellToSelect in cellsToSelect {
cellToSelect.backgroundColor = UIColor.lightGray
}
}
}
答案 2 :(得分:0)
确定如果它们的大小相同,则说100x100,然后获取您选择的单元格
向collectionView询问单元格的CGRect
找到中心。
然后向collectionView询问点,x - 100,x + 100,y - 100,y + 100的单元格。
然后看哪些不是零?