guarinex
guarinex

Reputation: 122

About addTarget for a button inside a UITableViewCell

I'm not able to understand why the addTarget in my UIButton is not working in a specific case.

So, there is a UITableViewCell where I create a button programmatically, like:

let myClickButton : UIButton = {
    let button = UIButton()
    button.setTitle("Hit Test", for: .normal)
    button.tintColor = UIColor.white
    button.addTarget(self, action: #selector(printMessage), for: .touchUpInside)
    button.isUserInteractionEnabled = true
    return button
}()

And, there is also the function in my UITableViewCell class that the button was supposed to be calling:

func printMessage(){
    print("button was clicked")
}

However, the printMessage function is never called and there is no error in the console. Could you help me understand what is the problem on this case? It seems to be the problem of being in a UITableViewCell as I definitely tested it on a regular viewController and it worked fine.

Thanks a ton!

Upvotes: 2

Views: 858

Answers (1)

Jonathan
Jonathan

Reputation: 2383

Depending on where the closure for the button is, I would try setting the target AFTER the UITableViewCell has been instantiated. Other than that, I'm not sure what the problem is without seeing more code.

Upvotes: 2

Related Questions