2

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!

guarinex
  • 110
  • 1
  • 10
  • Your code should work fine and without explicitly setting `isUserInteractionEnabled = true`. I've never tried passing a selector without letting the runtime know where to look for the method. But, as far as I know it will implicitly call the function on `self`. So, try qualifying the selector with the name of the class. For instance, `#selector(MyCustomTableViewCell.printMessage)`. – Jonathan Jul 28 '17 at 22:34
  • Also, this may be incorrect but I think I've read that you shouldn't use self in a block as it will be captured. Someone may need to correct me if I'm incorrect on this. – Jonathan Jul 28 '17 at 22:40
  • Hi Jonathan. thanks for your message. I tried to do that, but without success. It seems somehow `self` is not what `addTarget` is expecting in this case, trying to figure it out yet :( – guarinex Jul 28 '17 at 22:40
  • 2
    Hmmm.... 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. – Jonathan Jul 28 '17 at 22:47
  • 2
    Gosh! It worked. I added the target on the `awakeFromNib` method. Thank you, Jonathan! Much appreciated! – guarinex Jul 28 '17 at 22:51
  • Great! I posted the comment as an answer for other people. Please accept it whenever you get the chance. – Jonathan Jul 28 '17 at 23:02

1 Answers1

2

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.

Jonathan
  • 2,623
  • 3
  • 23
  • 38