Statt Farbe der Einstellung in didSelectItemAtIndexPath
legen Sie die Farbe in cellForItemAtIndexPath
für die Sie brauchen, um deklarieren Sie die Instanz Int
und speichern Sie die Zeile collectionView
innerhalb dieser Instanz wie folgt.
var selectedRow: Int = -1
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
// Set others detail of cell
if self.selectedRow == indexPath.item {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.clearColor()
}
return cell
}
Jetzt in didSelectItemAtIndexPath
setzen die selectedRow
die collectionView
neu zu laden.
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if self.selectedRow == indexPath.item {
self.selectedRow = -1
}
else {
self.selectedRow = indexPath.item
}
self.collectionView.reloadData()
}
Edit: Für mehrere Zellenauswahl ein Array von indexPath
erstellen und speichern Sie das Objekt von indexPath so.
var selectedIndexPaths = [NSIndexPath]()
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath:NSIndexPath)->UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CELL", forIndexPath: indexPath) as! InterestCollectionViewCell
// Set others detail of cell
if self.selectedIndexPaths.contains(indexPath) {
cell.backgroundColor = UIColor.redColor()
}
else {
cell.backgroundColor = UIColor.clearColor()
}
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if self.selectedIndexPaths.contains(indexPath) {
let index = self.selectedIndexPaths.indexOf(indexPath)
self.selectedIndexPaths.removeAtIndex(index)
}
else {
self.selectedIndexPaths.append(indexPath)
}
self.collectionView.reloadData()
}
Hallo Nirav, danke für deine Antwort. Es behebt die Probleme, bei denen mehr als eine Zelle aufgerufen wird und Farben sich zurück ändern können. Kennen Sie jedoch den Ansatz, die Mehrfachauswahl zu ermöglichen, sodass Benutzer auf mehr als einen Artikel tippen können? – WoShiNiBaBa
@WoShiNiBaBa Überprüfen Sie die bearbeitete Antwort für mehrere Auswahl :) –