iGotQuestions
iGotQuestions

Reputation: 15

Toggle image within uicollectionviewcell when clicked

I have a uicollectionview with a series of custom class cells that have a few textviews and a uibutton. With over 100 cells, I just want to toggle the uibutton image for each respective cell. The uibutton is a favorites button, and like most apps I just want to favorite and "un-favorite" different cells.

NOTE: I tried to add the gesture recognizer in the class directly, but for some reason the image changes, but it highlights multiple cells instead of the specific cell that was clicked

my code:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! SimpleExampleSubCell
        cell.backgroundColor = UIColor.init(white: 0.10, alpha: 0.25)
        cell.infoLine2TextVw.text = ""
        cell.infoLine3TextVw.text = ""
        if let heading_name = self.dict_dict_holder[indexPath.item]["Name"]{
            cell.headerTextVw.text = heading_name
            cell.infoLine1TextVw.text = self.dict_dict_holder[indexPath.item]["Phone"]
        }
        cell.bringSubview(toFront: cell.headerTextVw)
        cell.favorite_button.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AddFavorite(withSender:))))
        return cell
    }


    @objc func AddFavorite(withSender sender:UIButton){
        print("clicked")
        //The line below fails each time I run it.
        sender.setImage(newImage.png,.normal)
    }

Upvotes: 0

Views: 173

Answers (2)

Shehata Gamal
Shehata Gamal

Reputation: 100533

Replace

@objc func addFavorite(withSender sender:UIButton){
    

with

// not recommended use touchUpInside
@objc func addFavorite(_ sender:UITapGestureRecognizer){
  let btn = sender.view! as! UIButton
}

OR better

cell.favorite_button.addTarget(self, action:#selector(addFavorite), for: .touchUpInside)

    

Don't Add tapgestures to buttons , as they they have their own targets like touchUpInside or touchUpOutside and many more

table cells are reused you need to nil them inside cellForRowAt or give an else

if someCondition { 
   cell.favorite_button.setImage(newImage1.png,.normal)
else { 
  cell.favorite_button.setImage(newImage2.png,.normal)
}

Upvotes: 1

danywarner
danywarner

Reputation: 958

you have to set the default image (plus everything you want to reset) for each cell in the prepareForReuse() method so it clears up the reused content

Upvotes: 0

Related Questions