Muhamméd Muhamméd - 4 months ago 70
Swift Question

Why adding action to button in UICollectionViewCell not working well?

I Have CollectionView which has multiple dynamic cells , foreach cell have button which has action to add number of items here's my simple code :

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

}
}


and here's the method which adding items

func addItemsNumberToCart(sender:UIButton)
{

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

}


and here's my collectionViewCell class

import UIKit

class productsCollectionViewCell: UICollectionViewCell {


@IBOutlet weak var addItems: UIButton!

}


it's working and changing values but it's change values for multiple rows not only the selected row anybody now what's wrong ?

Answer

Looks like you are adding the target but never removing it. So as cells get reused, the buttons accumulate multiple targets. There are a few ways to solve this; one is to implement prepareForReuse in your productsCollectionViewCell class (which BTW should have an uppercase P):

class ProductsCollectionViewCell: UICollectionViewCell {
    @IBOutlet weak var addItems: UIButton!

    func prepareForReuse() {
        super.prepareForReuse()
        addItems?.removeTarget(nil, action: nil, forControlEvents: .AllEvents)
    }
}