Reputation: 19
I would like to ask a simple question : how can I give a variable to the action in the creation of a button ?
if for create the button use :
newButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
on Object-c i did
NSString *selectorName = [NSString stringWithFormat:@"Button%d:",index+1];
[newButton addTarget:self action:NSSelectorFromString(selectorName) forControlEvents:UIControlEventTouchUpInside];
and on Swift ?
Upvotes: 1
Views: 873
Reputation: 6657
You can store Swift Selector structs as a variable.
let sel : Selector = "buttonTapped:"
button.addTarget(self, action: sel)
If you want the selector to have a variable in it, you can simply add the variable to the string like this:
let sel : Selector = "button\(buttonNumber)tapped"
This makes use of Selector's adoption of the StringLiteralConvertible.
Selectors are mentioned in the Using Swift With Objective C ebook.
Upvotes: 0
Reputation: 2827
use NSSelectorFromString
let sel = NSSelectorFromString("Button\(index+1)")
newButton.addTarget(self, action: sel, forControlEvents:UIControlEvents.TouchUpInside)
Upvotes: 1