【问题标题】:Toggle image within uicollectionviewcell when clicked单击时在 uicollectionviewcell 中切换图像
【发布时间】:2019-02-16 22:33:41
【问题描述】:

我有一个带有一系列自定义类单元格的 uicollectionview,其中包含一些文本视图和一个 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


    【解决方案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)
    
        
    

    不要向按钮添加轻触,因为它们有自己的目标,例如 touchUpInside 或 touchUpOutside 等等

    表格单元格被重复使用,您需要在 cellForRowAt 中将它们设为 nil 或给出 else

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

    【讨论】:

    • 我根据您的建议更改了我的发件人选项,但是当我尝试编写行来设置图像时,我收到了一个未解决的标识符错误。
    • 这绝对有效,这就是我接受它作为答案的原因,但是当我向上滚动浏览我的单元格时,它似乎突出了同一个单元格的位置。例如,我有 100 多个单元格,但一次只能查看 4 个单元格。当我单击第一个单元格的按钮时,它会根据需要更改,但是当我向上滚动滚动后视图中显示的第一个单元格时,现在有一个突出显示的收藏夹按钮图像。它随着我滚动而改变。
    • 细胞被重复使用你想保存它的模型中每个细胞的当前状态
    • 你能举个例子吗?
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2016-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-28
      • 2013-01-11
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      相关资源
      最近更新 更多