Как сохранить выбранные индексные пути UICollectionViewCell, который находится внутри UITableViewCell, в массив?

У меня есть UICollectionViewCells внутри UITableView. Я пытаюсь выделить выбранный UICollectionViewCell для каждой строки UITableView. Когда UITableView перезагрузится, выбранные ячейки должны быть выделены. Вот пример кода:

var selectedIndexes = [IndexPath]()
var familyAModelArray : [[Child1]] = []
var childAModelArray : [Child1] = []

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return familyAModelArray[collectionView.tag].count

}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell

        cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray

        cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload])

     return cell
        }

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        selectedIndexes.append(indexPath)

        let i = selectedIndexes[collectionView.tag][indexPath.row]

}

Здесь я получил индекс вне диапазона:let i = selectedIndexes[collectionView.tag][indexPath.row]

Как этого добиться? Любая идея? Заранее спасибо.

1 ответ

Хороший способ проверить, выбираются ли ваши ячейки, это изменить цвет фона ячейки.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let cell = collectionView.cellForItemAt(indexPath)
    cell.backgroundColor = .red

    // append the selected red cells to an array like such
    selectedIndices.append(indexPath)


}

После перезагрузки tableView вы можете проверить свой массив на предмет выбранных индексов и изменить цвет фона.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {


    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ChildCollectionViewCell

    if selectedIndices.contains(indexPath) {
        cell.backgroundColor = .red
        // check if the index matches a selectedIndex and change it to the selected color.
    }
    cell.nameLabel.text = childAModelArray[indexPath.row].person! // or childArray

    cell.profilePicture.sd_setImage(with: URL(string: "\(baseUrl)\(childAModelArray[indexPath.row].image!)"), placeholderImage: #imageLiteral(resourceName: "avatar.png"), options: [.continueInBackground,.progressiveDownload])

 return cell
}

Теперь, как только он перезагрузится, функция cellForItemAt вызывается снова, и индексы на выбранных индексных путях снова будут красными.

Другие вопросы по тегам