首页 > 解决方案 > Swift4 - UIButton 在 UIView 中使用 addTarget 时出错

问题描述

这是required initUIVIew 中带有 addTarget的代码

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    hiddenButton = self.viewWithTag(9000) as? UIButton
    hiddenButton.addTarget(self, action: "hiddenCameraAction:", for: .touchUpInside)
}

这是我的选择功能

func hiddenCameraAction(_ sender: Any)  {
    //Do something
}

当我单击按钮时,UIView应用程序崩溃并出现错误:

TeachSystem[27065:8131674] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[TeachSystem.CameraView hiddenCameraAction:]: unrecognized selector sent to instance 0x121d11050' * First throw call stack: (0x1ee830ec4 0x1eda01a40 0x1ee749c24 0x21bb74558 0x1ee8367dc 0x1ee83848c 0x21bb48454 0x21b5d5d0c 0x21b5d602c 0x21b5d502c 0x21bb81bac 0x21bb82e10 0x21bb6210c 0x21bc30f68 0x21bc33960 0x21bc2c450 0x1ee7c11f0 0x1ee7c1170 0x1ee7c0a54 0x1ee7bb920 0x1ee7bb1f0 0x1f0a34584 0x21bb46d40 0x105039f40 0x1ee27abb4) libc++abi.dylib: terminating with uncaught exception of type NSException

问题:如何解决此错误?

标签: swiftuibutton

解决方案


动作应定义为#selector

hiddenButton.addTarget(self, action: #selector(hiddenCameraAction(_:)), for: .touchUpInside). 

推荐阅读