我在Cell中有一个收藏夹按钮。我已根据此收藏夹按钮DAVMEDIAfileId定义了不同的图像。如果选择“收藏夹”,否则选择。但是目前,DAVMEDIAfileId数组中的所有值都是true或false。我只希望它更改一个值。由于所有这些都改变了,所以它不起作用。我只希望fav按钮更改所选DAVMEDIAfileId [indexPath.row]
的值 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "davetiyeGosterCell", for: indexPath) as! davetiyeCell
cell.favCell.isSelected = !cell.favCell.isSelected
let key = "\(DAVMEDIAfileId[indexPath.row])"
let userDefault = UserDefaults.standard
userDefault.set(cell.favCell.isSelected, forKey: key)
userDefault.synchronize()
let keygetir = UserDefaults.standard.bool(forKey: "\(DAVMEDIAfileId[indexPath.row])")
if keygetir == true {
cell.favCell.setImage(UIImage(named: "heart"), for: .normal)
cell.favCell.setImageTintColor(UIColor.black)
cell.favCell.setImage(UIImage(named: "heart"), for: .selected)
cell.favCell.setImageTintColor(UIColor.red)
}
if keygetir == false {
cell.favCell.setImage(UIImage(named: "heart"), for: .normal)
cell.favCell.setImageTintColor(UIColor.red)
cell.favCell.setImage(UIImage(named: "heart"), for: .selected)
cell.favCell.setImageTintColor(UIColor.black)
}
}
答案 0 :(得分:0)
您可以尝试以下方法:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "davetiyeGosterCell", for: indexPath) as! davetiyeCell
let selected = UserDefaults.standard.bool(forKey: "keyIndex_\(DAVMEDIAfileId[indexPath.row])")
cell.favCell.isSelected = selected
cell.favCell.setImage(UIImage(named: "heart"), for: .normal) // I think, you should use empty heart
cell.favCell.setImage(UIImage(named: "heart"), for: .selected)
cell.favCell.tintColor = selected ? .red : .black
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "davetiyeGosterCell", for: indexPath) as! davetiyeCell
let selected = !UserDefaults.standard.bool(forKey: "keyIndex_\(DAVMEDIAfileId[indexPath.row])")
cell.favCell.isSelected = selected
cell.favCell.tintColor = selected ? .red : .black
let userDefault = UserDefaults.standard
userDefault.set(selected, forKey: "keyIndex_\(DAVMEDIAfileId[indexPath.row])")
userDefault.synchronize()
}