单击时在 uicollectionviewcell 中切换图像

Toggle image within uicollectionviewcell when clicked

我有一个带有一系列自定义 class 单元格的 uicollectionview,这些单元格有一些文本视图和一个 uibutton。有超过 100 个单元格,我只想切换每个单元格的 uibutton 图像。 uibutton 是一个收藏夹按钮,和大多数应用程序一样,我只想收藏和 "un-favorite" 个不同的单元格。

注意:我试图直接在 class 中添加手势识别器,但由于某种原因图像发生了变化,但它突出显示了多个单元格而不是被单击的特定单元格

我的代码:

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

替换

@objc func addFavorite(withSender sender:UIButton){
    

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

或更好

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

您必须在 prepareForReuse() 方法中为每个单元格设置默认图像(加上您要重置的所有内容),以便清除重复使用的内容