我目前有一个CollectionView
,其中有1个可重复使用的单元,其中填充了ImageView
。这个细胞被用来显示10个不同的动物10次(我提供细胞的图片)。我在这个集合视图上还有一个标签。每当用户按下一个单元格时,标签将变为“选定的动物名称”。 我现在想要的是让细胞图像在选择时变暗,并在未选中时恢复正常。截至目前,我知道如何通过手动将它切换成较暗的一个来更改单元格的图像,但我不知道如何在另一个单元格上更改为正常。 我该如何实施?我已经在底部抄我的代码:根据CollectionView中的选择更改ImageView
//cell configuration
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//define the cell
let cell = collectionview.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! AnimalSelectionCell
//animals is name of array of different types of animals
cell.animalImage.image = UIImage(named: animals[indexPath.row])
cell.animalImage.restorationIdentifier = animals[indexPath.row]
return cell
}
//choosing an animal
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let currentCell = collectionview.cellForItem(at: indexPath) as! AnimalSelectionCell
let animal = currentCell.animalImage.restorationIdentifier! //gets what type of animal selected
selectionLabel.text = "\(animal) selected" //changes label
currentCell.animalImage.image = UIImage(named: animal + "Selected") //changes to darker animal image
}
这给选定的动物一个更暗的图像,但每当我选择另一只动物时,我先前选择的动物图像仍然变暗。我该如何解决? – fphelp
另外我有一个清晰的按钮,当我按下它时,标签变为“没有选择动物”。我应该在IBAction代码中使用哪部分代码,因此当我按下清除按钮时,所有图像都将恢复正常? – fphelp
@fphelp检查我的答案我已经添加了一个clearSelection函数,您需要的实现为最后的requeriment –