Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

ios - UIButton image for normal state in collectionview cell repeats itself every four cells

I'm trying to set an image for a button's normal state which is located in a collectionView cell. When the button is pressed the image changes. The problem is every four cells it repeats the same image as the original cell when the button is pressed. Is there a way to not have it repeat itself and when the button is pressed its only for that individual cell?

Here is the code:

class FavoritesCell: UICollectionViewCell {

  var isFavorite: Bool = false

  @IBOutlet weak var favoritesButton: UIButton!

  @IBAction func favoritesButtonPressed(_ sender: UIButton) {
        _ = self.isFavorite ? (self.isFavorite = false, self.favoritesButton.setImage(UIImage(named: "favUnselected"), for: .normal)) : (self.isFavorite = true, self.favoritesButton.setImage(UIImage(named: "favSelected"), for: .selected))

    }
}

I've tried doing this but for some strange reason the 'selected' state image is never shown even when the button is pressed:

let button = UIButton()

override func awakeFromNib() {
    super.awakeFromNib()

    button.setImage(UIImage(named: "favUnselected"), for: .normal)
    button.setImage(UIImage(named: "favSelected"), for: .selected)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...