Невидимые ячейки UICollectionView не отменяются - Swift - PullRequest
0 голосов
/ 25 февраля 2020

В моем быстром приложении есть два представления коллекции. Один, который является категориями функций, а другой, который является функциями. Первый работает как фильтр для второго. Если я выберу «Cat1», то будут отображаться только функции с тегом «Cat1». Это прекрасно работает. Представление коллекции категорий функций является горизонтальным, и мне нужно прокрутить, чтобы увидеть все ячейки. Моя проблема / проблема уже упоминалась в других темах, но я не могу найти правильный ответ или метод.

Проблема: если я выберу категорию, фон ячейки изменится, хорошо. Если теперь я прокручиваю полностью до конца представления коллекции и выбираю последнюю ячейку, это одно изменение, как выбранное, при этом первая (ранее выбранная) не отменяется. Я знаю, что это проблема с повторно используемой ячейкой, но не знаю, как управлять который. Ниже мой код:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Working with functions categories collection view
      if collectionView == self.functionsCategoriesCollectionView {
          let cell = collectionView.cellForItem(at: indexPath) as! DevicePageFunctionsCategoriesCVCell
              cell.isHidden = false
              cell.cellView.isHidden = false
              cell.isSelected = true

              cell.cellView.clipsToBounds = true
              cell.cellView.layer.cornerRadius = 25
              cell.cellView.addGradiant(colors: [UIColor(red: 127.0/255.0, green: 127.0/255.0, blue: 127.0/255.0, alpha: 1.0).cgColor, UIColor(red: 47.0/255.0, green: 47.0/255.0, blue: 47.0/255.0, alpha: 1.0).cgColor], angle: 45)

          if cellSelectionIndexPath == indexPath {
              // it was already selected
              cellSelectionIndexPath = nil
              collectionView.deselectItem(at: indexPath, animated: true)
              cell.cellView.addGradiant(colors: [UIColor.clear.cgColor, UIColor.clear.cgColor], angle: 0)

              self.filtered = GlobalVariables.currentProduct.functions.filter { _ in
                  return true
              }

              self.functionsCollectionView.reloadData()

          } else {
              // wasn't yet selected, so let's remember it
              cellSelectionIndexPath = indexPath

              // Filter with seletec category name
              let cellCategoryName = ICDatabase.objects(FunctionCategory.self)[indexPath.row]

              self.filtered = GlobalVariables.currentProduct.functions.filter { function in
                  return function.functionCategory.contains(cellCategoryName)
              }

              self.functionsCollectionView.reloadData()
          }

      }
}

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

        if collectionView == self.functionsCategoriesCollectionView {

            if let cellToDeselect = collectionView.cellForItem(at: self.cellSelectionIndexPath) as? DevicePageFunctionsCategoriesCVCell {

                cellToDeselect.isSelected = false

                collectionView.deselectItem(at: self.cellSelectionIndexPath, animated: true)

                cellToDeselect.cellView.addGradiant(colors: [UIColor.clear.cgColor, UIColor.clear.cgColor], angle: 0)

                self.cellSelectionIndexPath = nil

                // Get all functions
                self.filtered = GlobalVariables.currentProduct.functions.filter { _ in
                    return true
                }

                self.functionsCollectionView.reloadData()
            }
        }
}

Спасибо за вашу помощь!

Ответы [ 2 ]

0 голосов
/ 25 февраля 2020

Ячейки коллекции повторно используют память. Таким образом, вы должны вручную управлять данными и пользовательским интерфейсом. Если вам требуется выбрать только одну ячейку категории в представлении коллекции в любое время, сохраните одну переменную в представлении коллекции и обновите ее с помощью метода didSelect.

var selectedIndexPath: IndexPath?

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    selectedIndexPath = indexPath
    collectionView.reloadData()
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = UICollectionCell()
    ....
    cell.backgroundColor = UIColor.black
    if indexPath == selectedIndexPath {
        cell.backgroundColor = UIColor.red
    } 
}
0 голосов
/ 25 февраля 2020

Попробуйте это -

var selectedIndexPath: IndexPath?

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)

        cell.layer.backgroundColor = UIColor.black

        self.selectedIndexPath = indexPath
    }

    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)

        cell.layer.backgroundColor = UIColor.white

        self.selectedIndexPath = nil
    }
...