i have collectionView. At the first launch I change color for first item to black. The problem is that when I select another item I want it to become black and first item become white. I use didSelectItemAtIndexPath and didDeselectItemAtIndexPath, but if i don't click the first item then I can't change it's color when I click another one. Can someone help me?
Can't deselect item in collectionView
1.5k Views Asked by lucca910 At
3
There are 3 best solutions below
0
On
set a selectedindexpath and reload collection view according to selected index path.
class CollectionViewController: UICollectionViewController {
var selectedIndexPath : IndexPath?
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "identifier", for: indexPath)
if indexPath == selectedIndexPath {
cell.backgroundColor = UIColor.black
} else {
cell.backgroundColor = UIColor.white
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPath = indexPath
collectionView.reloadData()
}
}
0
On
You can do it by following way.
Override the method in UICollectionViewCell Class like below
override var isSelected: Bool{
didSet{
if(self.isSelected){
yourView.backgroundColor = YourSelectedColor
}else{
yourView.backgroundColor = YourUnSelectedColor
}
}
}
No Need to do anything in didSelectItemAt or didDeSelectItemAt methods.
Your element from your data source array should somehow know about current state of cell. For example you can have property of your custom object:
in
didSelectItemAtmethod first change every element'sisSelectedproperty tofalseand then for selected element settrueand then reload data ofcollectionViewthen in
cellForRowAtchangebackgroundColorofcelldepends onisSelectedproperty of certain element in your data source arrayAlternatively you can just save
indexPathof selected cell as global variableand then in
cellForRowAtyou can setbackgroundColorof cell depends on condition ifindexPathis equal toselectedIndexPath