传递参数时无法识别的选择器 - TableView Cell中的UIButton | Swift iOS

时间:2016-10-11 15:17:38

标签: ios uitableview uibutton

之前我遇到过这个问题,但通常是由于没有在Storyboard中连接按钮或者在函数期待时没有传递参数,就像这里的大多数现有问题似乎都暗示的那样。但这一次,它既不是那些东西。

我在CellForRowAt方法中使用此代码在TableView单元格中创建一个按钮:

let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 50))
button.addTarget(self, action: Selector(("showPeople:")), for: UIControlEvents.touchUpInside)
button.tag = indexPath.row
cell.addSubview(button)

我已声明showPeople方法如下:

func showPeople(sender: UIButton) {
    print("pressed")
}

按下按钮时,程序崩溃并显示以下消息:

showPeople: unrecognized selector sent to instance

但是当我声明这样的方法时(删除参数):

func showPeople() {
    print("pressed")
}

并将选择器更改为Selector(("showPeople"))它工作正常,我想这意味着我传递参数的方式存在问题。为什么会这样?该函数需要一个参数,因此需要:

1 个答案:

答案 0 :(得分:1)

您的选择器中似乎缺少sender部分。

请改为尝试:

button.addTarget(self, action: #selector(ViewController.showPeople(sender:)), for: .touchUpInside)