Как вы храните состояние UICollectionViewCell?Желательно использовать его indexPath.
Вот некоторый фон и пример.
В настоящее время у меня есть сетка ячеек collectionView размером 10x10.Когда ячейка щелкается, она рекурсивно проверяет окружающие ячейки на наличие определенного условия, используя indexPath ячейки.
Вот проблема, иногда окружающие ячейки будут содержать исходную ячейку (ячейку, чей indexPath она использует для проверки окружающих ячеек), вызывая бесконечный цикл.Вот пример:
Ячейка в IndexPath [0, 0] выбрана, ячейка в [0, 0] обнаружена (я хотел бы сохранить этот факт) , а окружающие клетки: [ [0, 1] , [1, 1], [1, 0]].
Затем рекурсивный метод проверяет окружающие ячейки так же, как и для выбранной ячейки, [0, 0] - начиная с [0, 1] .Ячейка в indexPath [0, 1] обнаружена, и теперь она будет использоваться для проверки следующего набора окружающих ячеек.
Окружающие ячейки для [0,1] будут [ [0, 0 ], [1, 0], [0, 2], [1, 2], [1, 1]] - и здесь начинается проблема / возникает бесконечный цикл.
Каков наилучший способ сохранить состояние уже выявленной ячейки?Проверка, если ячейка isSelected не является опцией, потому что, как вы можете видеть с помощью [0,1], ячейки, которые не были выбраны, могут быть проверены.
Я должен упомянуть, что это пользовательская ячейка - будет ли создание Bool в этой пользовательской ячейке наилучшим способом приблизиться к ней?С сеткой из 100 ячеек мне кажется, что это может быть не лучшим решением.
РЕДАКТИРОВАТЬ:
Это проверяет окружающие ячейки, а затем делает рекурсивный вызов.Сначала recursiveCheck вызывается при выборе ячейки в методе didSelect.
//this checks for the nearby positions using the cell's indexpath that is being retrieved at didSelectItemAt IndexPath.
// all the variables like nearbyForLeftEdge are the different arrays that are used to know which surrounding areas to check since differnt parts of the grid have a different positions to check
func nearbyPositionsCheck(userLocation: IndexPath) -> [IndexPath] {
var nearbyLocation = [IndexPath]()
if edgeCases(userIndexPath: userLocation) != true && cornerCases(userIndexPath: userLocation) != true {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyCellsCoordinates, userLocation: userLocation)
} else if edgeCases(userIndexPath: userLocation) == true && cornerCases(userIndexPath: userLocation) == false {
if userLocation.row == 0 {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForLeftEdge, userLocation: userLocation)
} else if userLocation.section == 0 {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForTopEdge, userLocation: userLocation)
} else if userLocation.row == 9 {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForRightEdge, userLocation: userLocation)
} else if userLocation.section == 9 {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForBottomEdge, userLocation: userLocation)
}
} else if cornerCases(userIndexPath: userLocation) == true {
if userLocation == [0,0] {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyTopLeft, userLocation: userLocation)
} else if userLocation == [0,7] {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForBottomLeft, userLocation: userLocation)
} else if userLocation == [7,7] {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForBottomRight, userLocation: userLocation)
} else if userLocation == [7,0] {
nearbyLocation = idxPathsForEdges(idxPaths: nearbyForTopRight, userLocation: userLocation)
}
}
return nearbyLocation
}
func recursiveCheck(userLocation: IndexPath, cell: UICollectionView) {
var newLocation = userLocation
let nearbyCell = cell.cellForItem(at: newLocation) as? CustomCollectionViewCell
let nearbyPositions = nearbyPositionsCheck(userLocation: userLocation)
for nearby in nearbyPositions {
if cellNumber(nearbyCells: nearbyPositions) > 0 { // cell number returns the number of surrounding cells nearby that meet the condition to stop checking for cells, which is != 0
nearbyCell?.label.text = String(cellNumber(nearbyCells: nearbyPositions))
nearbyCell?.backgroundColor = .green
} else if cellNumber(nearbyCells: nearbyPositions) == 0 && nearbyCell?.isRevealed == false { //if the cell # does equal zero, call this function again until it does not.
// in both situations I want to reveal the cell
nearbyCell?.label.text = String(cellNumber(nearbyCells: nearbyPositions))
nearbyCell?.backgroundColor = .cyan
// I want to check the state of the cell before calling this. If I've already A) Selected the cell this shouldn't be checked or B)The cell has already been checked via recursion or otherwise, this shouldn't be checked
recursiveCheck(userLocation: nearby, cell: cell)
}
newLocation = nearby
}
} ````