var arrData = [String]() // This is your data array var arrSelectedIndex = [IndexPath]() // This is selected cell Index array var selectedSkills = [String]() // This is selected cell data array extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return arrData.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! CollectionViewCell if selectedSkills.contains(arrData[indexPath.row]) { cell.skillsView.backgroundColor = cell.skillsView.hexStringToUIColor(hex: "FEDA22") } return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("You selected cell #\(indexPath.item)!") if let cell = collectionView.cellForItem(at: indexPath) as? SkillsCollectionViewCell { let selectedCategory = subCategoriesPopUpArray[indexPath.item] if selectedSubCategories.contains(selectedCategory) { cell.skillsView.backgroundColor = cell.skillsView.hexStringToUIColor(hex: "F0F0F0") selectedSubCategories = selectedSubCategories.filter { $0 != selectedCategory } } else { selectedSubCategories.append(selectedCategory) cell.skillsView.backgroundColor = cell.skillsView.hexStringToUIColor(hex: "FEDA22") } } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter