我试图在didSelectItemAt的帮助下更改collectionviewcell中的UIImage。当我在开头选择单元格时它正在工作,但是当我向下滚动并向上滚动时,图像又恢复到它们的状态,并且更改的图像会移动到不同的单元格。
Scrolled down then came up Image
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
let tempString = "\(NSLocalizedString("base_url", comment: ""))\(itemImageLink[indexPath.row])"
let urlnew:String = tempString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!
let url = URL(string: urlnew)
cell.rateCardImage.kf.setImage(with: url,placeholder: UIImage(named: "Junkart_Bin.png"))
cell.label.text = itemName[indexPath.row]
cell.itemRate.text = itemRate[indexPath.row]
cell.layer.cornerRadius = 3
cell.card.backgroundColor = UIColor.white
cell.card.layer.masksToBounds = false
cell.card.layer.shadowColor = UIColor.black.withAlphaComponent(0.2).cgColor
cell.card.layer.shadowOffset = CGSize(width: 0, height: 0)
cell.card.layer.shadowOpacity = 1 //0.8
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! RateCardCollectionViewCell
if self.selectedRate == nil {
cell.changeImagetoSelected()
self.selectedRate = [Int]()
self.selectedRate.append(indexPath.row)
}
else {
}
}
以下是UICollectionViewCell类
class RateCardCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var rateCardImage: UIImageView!
@IBOutlet weak var card: UIView!
@IBOutlet weak var itemRate: UILabel!
@IBOutlet weak var selected_rate_image: UIImageView!
func changeImagetounSelected() {
selected_rate_image.image = UIImage(named: "unselected_rate")
}
func changeImagetoSelected() {
selected_rate_image.image = UIImage(named: "selected_rate")
}
}
请帮助!!
答案 0 :(得分:2)
检查在创建单元格cell
时selectedRate
上添加的cellForItemAt
创建索引。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collection_cell", for: indexPath) as! RateCardCollectionViewCell
// Your remaining codes are here.
if selectedRate.contains(IndexPath.row) {
cell.changeImageToSelected()
} else {
cell.changeImageTounselected()
}
return cell
}
答案 1 :(得分:1)
这是因为收集视图使他的细胞出列。因此,您需要在dataModel中保留您的选择,并获取是否选择了单元格。因此,在viewController和cellForItemAt方法调用中保留selectedIndex:
if(self.selectedIndex == indexPath.row){
cell.changeImageToSelected()
}
else{
cell.changeImageTounselected()
}
滚动时,这将保留您的选择