How create buttonAction functions dynamically in Swift

1.7k Views Asked by At

In a MCQ app I create multiple UIButton programatically like this

func createNewButton(buttonName: String, xPosition: CGFloat, yPosition: CGFloat) -> UIButton {
    let myButton = UIButton(frame: CGRectMake(0, 0, 50, 50))
    myButton.center = CGPoint(x: xPosition, y: yPosition)
    myButton.setImage(UIImage(named: buttonName), forState: UIControlState.Normal)
    myButton.addTarget(self, action: "buttonName:", forControlEvents: UIControlEvents.TouchUpInside)
    return myButton
}    

The problem is that in order to match a function to these buttons I need to create a function. The function should therefore looks like

func buttonName(sender: UIButton!) {
    // do some stuff
}        

These functions are actually going to save a string in an array, and the string to save is the name of the function itself. If we have for example buttonName: "blackberry", the code is going to set an image called "blackberry" and add a target action named "blackberry" and I would like therefore a buttonAction function called func blackberry(sender: UIButton) and this function would save the string "blackberry" in an array of String.

But all of this should be done in function of the initial buttonName: String parameter.

Or maybe I am really not doing things the right way, and how should I do then?

1

There are 1 best solutions below

2
On BEST ANSWER

How about this instead. Send all of your buttons to processButton(button: UIButton). When you create your buttons, set the tag property assigning a unique number to each button. Then you can have an array which translates the button tag to the string.

var buttonNames: [String] = []
var currentIndex = 0

func createNewButton(buttonName: String, xPosition: CGFloat, yPosition: CGFloat) -> UIButton {
    let myButton = UIButton(frame: CGRectMake(0, 0, 50, 50))
    myButton.center = CGPoint(x: xPosition, y: yPosition)
    myButton.setImage(UIImage(named: buttonName), forState: UIControlState.Normal)
    myButton.addTarget(self, action: "processButton:", forControlEvents: UIControlEvents.TouchUpInside)
    myButton.tag = currentIndex++
    self.buttonNames.append(buttonName)
    return myButton
}

func processButton(button: UIButton) {
    let string = buttonNames[button.tag]
    // process string
}