을 호출되는가에 대한 cellForItemAtIndexPath
의 색상을 설정을 수행해야 Int
의 인스턴스를 선언하고이 인스턴스에 collectionView
의 행을 이와 같이 저장합니다.
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
}
지금 didSelectItemAtIndexPath
에 selectedRow
가 collectionView
를 다시 설정합니다.
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if self.selectedRow == indexPath.item {
self.selectedRow = -1
}
else {
self.selectedRow = indexPath.item
}
self.collectionView.reloadData()
}
편집 : 다중 셀 선택은 indexPath
의 하나 개의 어레이를 만들고 같이 indexPath의 객체를 저장한다.
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()
}
안녕하세요 Nirav, 답변 해 주셔서 감사합니다. 둘 이상의 셀이 호출되고 색상이 다시 바뀔 수있는 문제를 수정합니다. 그러나 사용자가 하나 이상의 항목을 탭할 수 있도록 다중 선택을 허용하는 접근법을 알고 있습니까? – WoShiNiBaBa
@WoShiNiBaBa 다중 선택에 대한 편집 된 답변 확인 :) –