我尝试使用for循环创建多个按钮,但是我在使用(sender :)函数时遇到了问题。
我有以下代码
function _extendableBuiltin(cls) {
return function ExtendableBuiltin() {
return new cls(arguments);
}
当我按下按钮时,它会显示以下错误:
func setUpButtons(){
for i in 1...3 {
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 100, width: 75, height: 100))
btn.center = CGPoint(x: 20 + 100.0 * CGFloat(i), y: 200)
btn.backgroundColor = UIColor.green
btn.setTitle("Click Me", for: UIControlState.normal)
btn.addTarget(self, action: Selector(("buttonAction:")), for: UIControlEvents.touchUpInside)
btn.tag = i
self.view.addSubview(btn)
}
}
func buttonAction(sender: UIButton!) {
let btnsendtag: UIButton = sender
if btnsendtag.tag == 1 {
print("Button 1")
} else if btnsendtag.tag == 2 {
print("Button 2")
} else if btnsendtag.tag == 3 {
print("Button 3")
}
}
我觉得我有:正确,所以我不确定还有什么要找的。我使用的是swift 3.0。
答案 0 :(得分:3)
您的Selector(("buttonAction:"))
可能是您遇到问题的原因。
请尝试#selector(buttonAction(sender:))
。
答案 1 :(得分:1)
使用此
func setUpButtons(){
for i in 1...2 {
let btn: UIButton = UIButton(frame: CGRect(x: 100, y: 100, width: 75, height: 100))
btn.center = CGPoint(x: 20 + 100.0 * CGFloat(i), y: 200)
btn.backgroundColor = UIColor.greenColor()
btn.setTitle("click", forState: UIControlState.Normal)
btn.addTarget(self, action:#selector(buttonAction), forControlEvents: .TouchUpInside)
self.view.addSubview(btn)
}
}
答案 2 :(得分:1)
对于Swift 4 -
override func awakeFromNib() {
button.addTarget(self, action: #selector(buttonClicked), for: UIControlEvents.touchUpInside)
}
@objc func buttonClicked(sender:UIButton) {
...
}
答案 3 :(得分:0)
对于iOS Facebook SDK按钮,
将UIButton中的Button类分配给FBSDKLoginButton,然后运行应用程序
在设置委托,按钮权限时有效。
答案 4 :(得分:0)