简体   繁体   中英

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()

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];

}

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM