TheBlueTurtle TheBlueTurtle - 1 year ago 47
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 (

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

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

Anyone has an idea to fix it please ?


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)