Adding button programmatically swift

1.5k Views Asked by At

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.

2

There are 2 best solutions below

0
ingAlioth On BEST ANSWER

Change with

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

this is ok:

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

works for me

1
dktaylor On

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")
}