Swift中的“addTarget”在“TouchUpInside”上出错

3

我在视图上添加了一个按钮,并使用addTarget绑定事件,以调用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")
    }
}
}

为什么?!!

2个回答

5
只需从您的选择器中删除:,您的代码即可变为:
btn.addTarget(self, action: Selector("testp"), forControlEvents: UIControlEvents.TouchUpInside)

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

如果你的函数有像下面展示的参数,可以使用"testp:"

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

谢谢,那是一个问题,我们仍然有另一个问题,就是我应该把 func testp 放在UIViewController类中而不是 func viewDidLoad 中。 - Mofei Zhu

0

最终,我搞定了

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)

        //!!!!!!remove ":" for testp
        //btn.addTarget(self, action: Selector("testp:"), forControlEvents: UIControlEvents.TouchUpInside);
        btn.addTarget(self, action: Selector("testp"), forControlEvents: UIControlEvents.TouchUpInside);

        self.view.addSubview(btn)
        //I should put testp out of viewDidLoad
        //I should put testup UIViewController
        //func testp(){
        //    println("tttt")
        //}
    }

    // put testp here it's work
    func testp(){
        println("tttt")
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接