ios - 传递参数时无法识别的选择器 - TableView 单元格中的 UIButton | swift iOS

标签 ios uitableview uibutton

我以前遇到过这个问题,但通常是因为没有在 Storyboard 中连接按钮,或者在函数需要一个参数时没有传递参数,就像这里的大多数现有问题似乎暗示的那样。然而这一次它不是那些东西。

我在 CellForRowAt 方法中使用以下代码在我的 TableView Cell 中创建一个按钮:

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")) 它工作正常,我猜这意味着我传递参数的方式存在问题。为什么会这样?该函数需要一个参数,因此需要 :

最佳答案

看起来您的选择器中缺少 sender 部分。

试试这个:

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

关于ios - 传递参数时无法识别的选择器 - TableView 单元格中的 UIButton | swift iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980736/

相关文章:

ios - 将 JSON 数据加载到 TableView 不起作用

ios - 重置导航栏

objective-c - UITextField 拒绝允许用户输入

iOS UITextView 不允许选择 UITableViewCell

ios - 使用圆形按钮创建关卡选择屏幕

ios - 将dylib添加到 "Link Binary With Libraries"和添加到 "Other Linker Flags"有什么区别

performance - 我可以完全优化吗?

ios - ViewForHeaderInSection 代码仅适用于 header 出列

iphone - 为自定义 UIButton 子类设置操作

ios - 立即调用 CATransaction 完成