Levit Kanner
Levit Kanner

Reputation: 121

Buttons in collectionViewCell not triggering functions

I created a button in a supplementary collectionView cell as header and added a button with a target to it but it doesn't trigger the function when tapped. What am I doing wrong?

Below is the button I created and its target function in the cell class.

let dummyButton :UIButton = {
    let button = UIButton(type: .system)
    button.setTitle("Dummy", for: .normal)
    button.layer.cornerRadius = 3
    button.layer.borderWidth = 1
    button.titleLabel?.font = UIFont.systemFont(ofSize: 12)
    button.tintColor = UIColor.brown
    button.addTarget(self, action: #selector(handleTrash), for: .touchUpInside)
    return button
}() 


@objc func handleTrash (){
    print("It worked this time around so what was going on?")
}

I wrote all these in the collectionView Cell subclass. Please help

Upvotes: 1

Views: 70

Answers (2)

Levit Kanner
Levit Kanner

Reputation: 121

I found the solution. I had to declare the buttons as Lazy variables.

Upvotes: 2

Cristi Dumitrache
Cristi Dumitrache

Reputation: 150

Add the sender

button.addTarget(self, action: #selector(handleTrash(_:)), for: .touchUpInside)

@objc func handleTrash (_ sender: UIButton){
    print("It worked this time around so what was going on?")
}

Upvotes: 0

Related Questions