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?
How about this instead. Send all of your buttons to
processButton(button: UIButton)
. When you create your buttons, set thetag
property assigning a unique number to each button. Then you can have an array which translates the button tag to the string.