在 swift 中选择新行时,Collectionview 取消选择所选行

Collectionview deselect selcted row when selecting new row in swift

我正在做一个示例 collectionView 项目 swift.It 显示 10 行 vertically.I 更改了选定的背景颜色 row.How 在 collectionview 中选择新行时我是否取消选择选定行的背景颜色

代码:

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

将此代码转换为 swift 您将得到结果:

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

}

这正是您所需要的。设置在 cellForItemAtIndexPath 里面,你不需要关心什么时候取消选择手动完成。

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

        return cell
    }