gpt4 book ai didi

TouchUpInside 上的 Swift addTarget 错误

转载 作者:搜寻专家 更新时间:2023-10-31 22:15:27 24 4
gpt4 key购买 nike

我在 View 上添加了一个按钮,并使用 addTarget 绑定(bind)事件来调用 self.testp,但是当我运行它时,发生了一个错误:

2015-06-19 23:08:29.237 UI[16978:1700826] -[UI.ViewController testp:]: unrecognized selector sent to instance 0x7864d4a0
2015-06-19 23:08:29.240 UI[16978:1700826] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UI.ViewController testp:]: unrecognized selector sent to instance 0x7864d4a0'

代码是:

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
var btn:UIButton = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton
btn.frame = CGRectMake(10, 150, 100, 30)
btn.setTitle("button", forState: UIControlState.Normal)

//!!!!!!DID NOT WORK
btn.addTarget(self, action: Selector("testp:"), forControlEvents: UIControlEvents.TouchUpInside);

self.view.addSubview(btn)

func testp(){
println("tttt")
}
}
}

为什么?!!

最佳答案

只需从您的选择器中删除 :,您的代码将是:

btn.addTarget(self, action: Selector("testp"), forControlEvents: UIControlEvents.TouchUpInside)

并将您的函数放在 viewDidLoad 方法之外,但放在 ViewController 类中。

如果您的函数有如下所示的参数,您可以使用 "testp:":

func testp(yourArgument: String){
println("tttt")
}

关于TouchUpInside 上的 Swift addTarget 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30941631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com