I have created reusable cell with include a button in a XIB for a collection.
I can change the text of labels and buttons in the collection view but i can't get on click event.
I have tried below options:
a. This in UICollectionViewCell : Not working
class cellVC: UICollectionViewCell {
@IBOutlet weak var sampleLabel: UILabel!
@IBOutlet weak var buttonClicked: UIButton!
@IBAction func buttonTest(_ sender: Any) {
print("dsfsdf 111111")
}
}
b. I have also tried : Not working
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell : cellVC = collectionView.dequeueReusableCell(withReuseIdentifier: "cellVC", for: indexPath) as! cellVC
cell.sampleLabel. = "sample text"
cell.buttonClicked.tag = indexPath.row
cell.buttonClicked.addTarget(self, action: #selector(masterAction(sender:)), for: .touchUpInside)
cell.buttonClicked.backgroundColor = UIColor.cyan
return cell
}
func masterAction(_ sender: UIButton) {
print ("button click")
}
As both solutions are not working, how do i achieve this.
Thanks
This sometimes happen when the button is linked to the File's Owner instead of your cell.
Right click on the button in IB and check if the referencing outlet is correct, this should be your cell and not the File's Owner like in the image below: