0

имеем на странице два UICollectionView например

var selectedIndex = Int ()

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

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

    if(collectionView == self.collectionView) {

        cell.name_category.text = heroes[indexPath.row].category_name

        if selectedIndex == indexPath.row
        {
            cell.backgroundColor = UIColor.green
        }
        else
        {
            cell.backgroundColor = UIColor.red
        }

    }

    if(collectionView == self.collectionViewData) {
            cell.name_news.text = heroes[indexPath.row].name
            cell.text_news.text = heroes[indexPath.row].desc


    }


    return cell;

}


func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
   // return print(indexPath.row)
    selectedIndex = indexPath.row

   // self.collectionView.reloadData()
}

но не могу решить проблему с выделением ячейки в конкретной коллекции. Если выделить одну ячейку в одной коллекции то она будет и на другой отражатся

1 ответ 1

0

У Вас с каждой UICollectionView работа должна быть отдельно. Сейчас же один индекс строки для обеих.
Рассмотрите пример, набросал для наглядности один из вариантов. Каждой UICollectionView присваиваем тег по которому различаем с какой из них взаимодействуем:

class ViewController: UIViewController {

    @IBOutlet weak var collectionView1: UICollectionView!
    @IBOutlet weak var collectionView2: UICollectionView!

    var collectionViewTestModel1: [Bool] = [true, false, false, false]
    var collectionViewTestModel2: [Bool] = [true, false, false, false, false]

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView1.tag = 0
        collectionView2.tag = 1 // Присваиваем тег чтобы различать

        collectionView1.delegate = self
        collectionView2.delegate = self

        collectionView1.dataSource = self
        collectionView2.dataSource = self
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // Обрабатываем выделение и делаем reload этой cell
        if collectionView.tag == 0 {
            collectionViewTestModel1[indexPath.row] = !collectionViewTestModel1[indexPath.row]
        } else {
            collectionViewTestModel2[indexPath.row] = !collectionViewTestModel2[indexPath.row]
        }
        collectionView.reloadItems(at: [indexPath])
    }
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CellTest", for: indexPath)

        // Определяем ячейка выделена или нет и устанавливаем цвет
        var isCellSelected: Bool
        if collectionView.tag == 0 {
            isCellSelected = collectionViewTestModel1[indexPath.row]
        } else {
            isCellSelected = collectionViewTestModel2[indexPath.row]
        }
        cell.backgroundColor = isCellSelected ? .green : .orange

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // Отдаем количество ячеек в каждой из UICollectionView
        if collectionView.tag == 0 {
            return collectionViewTestModel1.count
        } else {
            return collectionViewTestModel2.count
        }
    }
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.