我正在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()
答案 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
}