I am using a UICollectionView and I am thinking how to add buttons for each collection view cell and I don't want all buttons to do the same actions. I need to change buttons actions. I don't know how to do that.
import UIKit
class FirstARViewController: UIViewController , UICollectionViewDelegate , UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
var imagescv = ["cv1","cv2","cv3","cv4","cv5"]
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return imagescv.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! cellimagesar
cell.layer.cornerRadius = 5
cell.layer.borderWidth = 1
cell.myImages.image = UIImage(named: imagescv [indexPath.row])
cell.myImages.contentMode = .scaleToFill
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 182, height: 290)
}
}
Assign the tag and action to the button inside the collectionviewcell.
Assign indexPath.item as button tag is the best approach to identify the particular button from the number of cells.
All you need to do within cellForItemAt delegate method.
cell.btnCounter.tag = indexPath.item
cell.btnCounter.addTarget(self, action: #selector(self.buttonClicked), for: .touchUpInside)
And now you just need to handle the event as below
func buttonClicked(_ sender: UIButton) {
//Here sender.tag will give you the tapped Button index from the cell
//You can identify the button from the tag
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With