user3823935
user3823935

Reputation: 891

Collectionview deselect selcted row when selecting new row in swift

I am doing a sample collectionView project in swift.It shows 10 rows vertically.I changed background color for selected row.How do i deselect selected row background color when selecting new row in collectionview

code:

for indexPath in collectionView .indexPathsForSelectedItems(){
            collectionView .deselectItemAtIndexPath(indexPath as? NSIndexPath, animated:false)
        } 
let Cell = collectionView.cellForItemAtIndexPath(indexPath)
Cell?.backgroundColor = UIColor .orangeColor()

Upvotes: 0

Views: 4120

Answers (2)

Sahabe Alam
Sahabe Alam

Reputation: 36

Convert this code to swift you will get result:

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{

UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor magentaColor];

}

-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{

UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    cell.backgroundColor = [UIColor greenColor];

}

Upvotes: 1

benLIVE
benLIVE

Reputation: 597

This is exactly what you need. Setting it inside cellForItemAtIndexPath, you don't need to care when is deselected for doing it manually.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    //...
        var bgColorView = UIView()
        bgColorView.backgroundColor = UIColor.whiteColor()
        cell.selectedBackgroundView = bgColorView

        return cell
    }

Upvotes: 1

Related Questions