Ios 如何将目标操作添加到UITableViewCell

Ios 如何将目标操作添加到UITableViewCell,ios,swift,uitableview,Ios,Swift,Uitableview,我已将一个按钮添加到特定的UITableViewCell。当我选择按钮时,会发生崩溃: 带按钮 libc++abi.dylib:以NSException类型的未捕获异常终止 在cellForRowAt的开头,我定义了按钮: let myButton = UIButton(type: .custom) myButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20) myButton.addTarget(self, action: #select

我已将一个按钮添加到特定的UITableViewCell。当我选择按钮时,会发生崩溃:

带按钮
libc++abi.dylib:以NSException类型的未捕获异常终止

cellForRowAt
的开头,我定义了按钮:

let myButton = UIButton(type: .custom)
myButton.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
myButton.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
myButton.tintColor = UIColor.yellow()
对于indexpath.row,我附加如下按钮:

cell.accessoryView=myButton作为UIView

操作
buttonatted
尝试加载不同的ViewController

我得到确认按钮操作有效(调用了例程)。 例行程序如下:

func buttonTapped() {
    print("ButtonTapped")

    let myPickerController = self.storyboard?.instantiateViewController(withIdentifier: "picker") as? MyPickerController
    print("1")
    self.present(myPickerController!, animated: true)
    print("2")
}
正如您从日志中看到的,我确实看到调用了例程,但我没有看到崩溃前的打印值1或2。有人知道我做错了什么吗

添加目标类

 myButton.addTarget(self, action: #selector(YourControllerName.buttonTapped(_:)), for: .touchUpInside)
然后改变你的函数,比如

 func buttonTapped(sender : UIButton){

 ....
 }

希望这对您有所帮助。

谢谢Jigar。第一行(addTarget)失败,原因是“类型为“MyViewController”的值没有成员“myButtonTapped”`您是否在控制器中使用给定名称定义了方法?像
buttonTapped
我想你的按钮动作是在其他视图控制器中..?“你在你的控制器中用给定的名称定义方法了吗?”。。是的,按钮工作-我可以看到函数被调用。。崩溃就在那之后,记住表视图单元格被重用;不确定每次添加一个新按钮是否明智。也许每个单元格已经有一个按钮,并在每次将单元格出列时重新配置它。您可以使用
nil
参数将所有目标/操作重置为
removeTarget…
:好主意。我想我已经试过了,但我会检查的。我已将按钮设置为全局变量。我称之为特定的细胞需要它。我可以看到这个按钮激活了这个功能,但是我还是会崩溃。。欢迎其他想法。哦,一次只存在一个按钮。您说过您“在cellForRowAt的开头”实例化它,这是表需要显示的每个单元格调用一次。即使有一个按钮被重用,也要确保不要多次添加同一个目标。Oops。我已经这样设置了,但是我接受了您的观点,并将创建按钮移动到viewDidLoad。抱歉搞混了