TheBlueTurtle TheBlueTurtle - 2 years ago 97
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 ?

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download