BoledgiDev
BoledgiDev

Reputation: 1198

Swift 3: button on collectionview

I added a button to my prototype cell of UICollectionView and I want to update a property showed in a label of the cell:

There's a button over the 28 and I want when taped add 1 to this integer

Thank's a lot

EDIT: Probably need to create a function who also get the indexPath.row but don't know how do this.

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
    //var cell :CounterCollectionViewCell!
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CounterCollectionViewCell

    // Configure the cell
    let myColor :UIColor = UIColor(red: 240/255, green: 179/255, blue: 28/255, alpha: 1.0)
    let presentCounter = counters[indexPath.row]
    cell.nameLabel.text = presentCounter.nameCD
    cell.valueLabel.text = String(presentCounter.valueCD)
    cell.backgroundColor = myColor
    cell.layer.cornerRadius=10

    return cell
}

@IBAction func masterCellAction() {

}

Upvotes: 1

Views: 4505

Answers (3)

Mohsen Hosseinpour
Mohsen Hosseinpour

Reputation: 534

on cellForItem add the action as a selector to your custom button which you added to your custom cell like this

cell?.customButton.addTarget(self, action: #selector(masterCellAction), for: .touchUpInside)

Edit:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 cell.masterButton.addTarget(self,action: #selector(masterAction(_:)),for: .touchUpInside) 
return cell 
} 
func masterAction(_ sender: UIButton) 
{ 
    let indexPath = collectionView?.indexPath(for: ((sender.superview?.superview) as! CounterCollectionViewCell))

let presentCounter = counters[indexPath.row] presentCounter.valueCD = presentCounter.valueCD + 1 
}

Upvotes: 1

anckydocky
anckydocky

Reputation: 76

You can make a custom class (eg. CustomButton) which inherits UIButton and add a property indexPath of type NSIndexPath. Then, make all your buttons of type CustomButton and you can easily know which cell you are updating.

Upvotes: 0

Xuan-Gieng Nguyen
Xuan-Gieng Nguyen

Reputation: 846

I think you should have 2 solutions like these:

  1. Create your own cell's class. That means the button will handle tap event itself. By this way, you need to create a new UICollectionViewCell subclass.
  2. Assume that when user select the cell (I mean user can tap any where in the cell), you just need to implement didSelectAtCell function, handle the cell by indexPath.

Hope it helps.

Upvotes: 0

Related Questions