我想问一个简单的问题: 如何在创建按钮时为动作提供变量?
如果创建按钮使用:
newButton.addTarget(self, action: "buttonAction:", forControlEvents: UIControlEvents.TouchUpInside)
在Object-c上我做了
NSString *selectorName = [NSString stringWithFormat:@"Button%d:",index+1];
[newButton addTarget:self action:NSSelectorFromString(selectorName) forControlEvents:UIControlEventTouchUpInside];
和Swift?
答案 0 :(得分:1)
使用NSSelectorFromString
let sel = NSSelectorFromString("Button\(index+1)")
newButton.addTarget(self, action: sel, forControlEvents:UIControlEvents.TouchUpInside)
答案 1 :(得分:0)
您可以将Swift Selector结构存储为变量。
let sel : Selector = "buttonTapped:"
button.addTarget(self, action: sel)
如果您希望选择器中包含变量,您只需将变量添加到字符串中,如下所示:
let sel : Selector = "button\(buttonNumber)tapped"
这使用Selector采用StringLiteralConvertible。