The cell is most likely reused and your isFavorite
is set to true
.
Just try adding
func prepareForReuse() {
super.prepareForReuse()
self.isFavorite = false
}
This will set the button to original image when cell is to be reused.
Also since you have your button have two states for selected
why do this dance
_ = self.isFavorite ? (self.isFavorite = false, self.favoritesButton.setImage(UIImage(named: "favUnselected"), for: .normal)) : (self.isFavorite = true, self.favoritesButton.setImage(UIImage(named: "favSelected"), for: .selected))
where you could only say self.favoritesButton.selected = self.isFavorite
Change your cell code to:
class FavoritesCell: UICollectionViewCell {
@IBOutlet weak var favoritesButton: UIButton!
var isFavorite: Bool = false {
didSet {
favoritesButton.selected = isFavorite
}
}
@IBAction func favoritesButtonPressed(_ sender: UIButton) {
favoritesButton.selected = !favoritesButton.selected
}
override func prepareForReuse() {
super.prepareForReuse()
isFavorite = false
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…