Uicollectionview在swift中选择新行时取消选择所选行

时间:2015-02-19 09:04:36

标签: ios swift xcode6 uicollectionview

我正在swift中做一个示例collectionView项目。它在垂直方向上显示10行。我更改了所选行的背景颜色。在collectionview中选择新行时,如何取消选择所选行背景颜色

代码:

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

2 个答案:

答案 0 :(得分:1)

将此代码转换为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];

}

答案 1 :(得分:1)

这正是您所需要的。在cellForItemAtIndexPath中设置它,您无需关心何时取消选择手动操作。

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

        return cell
    }
相关问题