TheBlueTurtle TheBlueTurtle - 7 months ago 17
Swift Question

Multiple buttons for one action without IB

In my view controller, I have 10 buttons. Each button has a tag and all the buttons call the same action (separate by a switch (sender.tag), case 0 -> case 9 to differentiate which button is selected).
I made with IB, connected all the buttons (

@IBOutlet
) to the same
@IBAction
and everything is good. But now I want to do this programmatically, without IB.

So I removed the
@IBOutlet
's and the
@IBAction
to create new buttons (
let myButton1 = UIBUtton()
) and a new action (
func newAction(sender: UIButton)
). I tried an
addTarget:
with the same selector for all the new buttons, but the app crashes.

Anyone has an idea to fix it please ?

Answer

This should work:

func newAction(sender: UIButton) {
    ...
}
...
myButton1.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside)
myButton2.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside)
myButton3.addTarget(self, action: "newAction:", forControlEvents: .TouchUpInside)