0

I am trying to add button programmatically, I created button, it shows in app, but problem that when I write .addTarget in #selector occurs error (it builds successfully, but action do not work) I tried to write playAction() and playAction(sender:) and playAction. None of them work. enter image description here

playPauseButton.addTarget(self, action: #selector(playAction(sender:)), for: .touchUpInside)

@objc
func playAction(sender: UIButton){
    print("Hello")
}

UPD: I solved by creating just system button and changed it. Maybe my Xcode have bug and because of that occurs error.

  • so ... you cant see Hello ? – Jawad Ali Jun 04 '20 at 19:06
  • Show how you setup and adding your button – vpoltave Jun 04 '20 at 19:49
  • This syntax is fine. Given how you defined your function, the `#selector(playAction(sender:))` syntax is correct. The problem rests elsewhere (e.g. with breakpoint/log statement, make sure you’re even hitting this `addTarget` line; use view debugger to confirm that the button has “user interaction” enabled and that there’s not something in front of this button that might be consuming the touches; etc.). – Rob Jun 04 '20 at 20:54
  • Also, I might suggest stepping away from your current project. Make a [MCVE](https://stackoverflow.com/help/mcve) by creating a blank project and adding the bare essentials to manifest the problem. Often when preparing a MCVE, you’ll often figure out the source of the problem yourself. And if not, you’ll have a minimal project that you can upload, that we can look at. – Rob Jun 04 '20 at 20:56
  • Is the button the only thing in your `UIView`? Is it possible there is another view overlapping this one or its interaction is disabled? Check the Debug view hierarchy just to be clear. – Rikh Jun 04 '20 at 23:45

2 Answers2

0

Your function needs to have the @objc attribute. This allows it to be looked-up as a selector.

@objc
func playAction(sender: UIButton) {
      print("Hello")
}
dktaylor
  • 874
  • 7
  • 12
0

Change with

playPauseButton.addTarget(self, action: #selector(playAction), for: .touchUpInside)

this is ok:

@objc
func playAction(sender: UIButton) {
      print("Hello")
}

works for me

ingAlioth
  • 59
  • 5