【问题标题】:Why adding action to button in UICollectionViewCell not working well?为什么向 UICollectionViewCell 中的按钮添加操作效果不佳?
【发布时间】:2016-07-31 20:18:45
【问题描述】:

我有 CollectionView,它有多个动态单元格,foreach 单元格有按钮,可以添加项目数量这是我的简单代码:

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    if ids.count == 0
    {
        return 3
    }else
    {
    return ids.count
    }

}




func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {


    if ids.count == 0
    {
        let cell = myCollection.dequeueReusableCellWithReuseIdentifier("loadingItems", forIndexPath: indexPath)

        return cell


    }else
    {
  let  cell =myCollection.dequeueReusableCellWithReuseIdentifier("cellProduct", forIndexPath: indexPath) as! productsCollectionViewCell

      cell.addItems.addTarget(self, action: #selector(homeViewController.addItemsNumberToCart(_:)), forControlEvents: UIControlEvents.TouchUpInside) 
  }







    return cell

    }
}

这是添加项目的方法

func addItemsNumberToCart(sender:UIButton)
{

sender.setTitle("Added to cart", forState: UIControlState.Normal)

}

这是我的 collectionViewCell 类

import UIKit

class productsCollectionViewCell: UICollectionViewCell {


    @IBOutlet weak var addItems: UIButton!

}

它正在工作并改变值,但它改变了多行的值,不仅是选定的行,现在有什么问题吗?

【问题讨论】:

    标签: swift uibutton uicollectionview uicollectionviewcell


    【解决方案1】:

    看起来您正在添加目标但从未删除它。因此,当单元格被重用时,按钮会累积多个目标。有几种方法可以解决这个问题;一种是在你的productsCollectionViewCell 类中实现prepareForReuse(顺便说一句,它应该有一个大写的P):

    class ProductsCollectionViewCell: UICollectionViewCell {
        @IBOutlet weak var addItems: UIButton!
    
        func prepareForReuse() {
            super.prepareForReuse()
            addItems?.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
        }
    }
    

    【讨论】:

    • 对不起,这是我的错误,它正在工作:) 谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 2012-09-23
    • 2015-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多