单击时在uicollectionviewcell内切换图像

问题描述 投票:0回答:2

我有一个带有一些自定义类单元格的uicollectionview,它们有一些textview和一个uibutton。有超过100个单元格,我只想切换每个相应单元格的uibutton图像。 uibutton是一个收藏夹按钮,和大多数应用程序一样,我只想收藏和“不喜欢”不同的单元格。

注意:我尝试直接在类中添加手势识别器,但由于某种原因图像更改,但它突出显示多个单元格而不是单击的特定单元格

我的代码:

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)
    }
ios swift uicollectionview uicollectionviewcell uitapgesturerecognizer
2个回答
1
投票

更换

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

不要在按钮上添加tapgestures,因为他们有自己的目标,如touchUpInside或touchUpOutside等等

表格单元格被重用你需要在cellForRowAt中取消它们或者给出一个else

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.