无法识别的选择器发送到类 [英] Unrecognized selector sent to class
问题描述
我已经看到,这是一个常见问题,但我找不到任何适合自己的解决方案.
I've seen that, this is a common issue but i couldn't find any solution for myself.
代码如下:
class ButtonViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(button)
}
func exmp(sender: UIButton) {
print("hello world")
}
let button: UIButton = {
let but = UIButton(frame: CGRect(x: 33, y: 33, width: 33, height: 33))
but.setTitle("-", for: .normal)
but.titleLabel?.textColor = UIColor.white
but.layer.cornerRadius = 10
but.backgroundColor = UIColor.red
but.addTarget(ButtonViewController.self, action: #selector(ButtonViewController.exmp(sender:)), for: .touchDown)
return but
}
}
问题:出现红色按钮,但当我点击它时,我收到无法识别的选择器发送到类"错误.
Issue: The red button appears but when i click it i get the "Unrecognized selector sent to class" error.
感谢任何帮助!谢谢.
推荐答案
您收到无法识别的选择器发送到类,因为您设置了错误的目标.目标应该是 self
而不是 ButtonViewController.self
:
You are getting Unrecognized selector sent to class because you have set the wrong target.
The target should be self
and not ButtonViewController.self
:
but.addTarget(self, action: #selector(ButtonViewController.exmp(sender:)), for: .touchDown)
您的 #selector
有效,但对于 Swift 3,您应该将操作编写为 func exmp(_ sender: UIButton) {
制作选择器 #selector(exmp(_:))
.注意:无论是否重写exmp
,都可以将选择器简化为#selector(exmp)
.
Your #selector
works, but for Swift 3 you should write the action as func exmp(_ sender: UIButton) {
making the selector #selector(exmp(_:))
. Note: whether or not you rewrite exmp
, you can simplify the selector to just #selector(exmp)
.
这篇关于无法识别的选择器发送到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!