无法识别的select器发送到类

我已经看到,这是一个常见的问题,但我找不到任何解决scheme。

这里是代码:

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 } } 

问题:红色button出现,但是当我点击它,我得到“无法识别的select器发送到类”错误。

任何帮助表示赞赏! 谢谢。

你正在得到无法识别的select器发送到类,因为你已经设置了错误的目标。 目标应该是self而不是ButtonViewController.self

 but.addTarget(self, action: #selector(ButtonViewController.exmp(sender:)), for: .touchDown) 

你的#selector工作,但是对于Swift 3,你应该写作为func exmp(_ sender: UIButton) {使select器#selector(exmp(_:)) 。 注意:无论是否重写exmp ,都可以简化select器到#selector(exmp)

所以我一直在寻找这个问题2天。 正确的addTarget方法必须是这样的:

 but.addTarget(self, action: #selector(ButtonViewController.exmp(sender:)), for: .touchDown) 

但是对我来说还有一个问题,就是“命令因信号失败:分段错误:11”

当我试图在viewDidLoad()方法中创build我的button时,没有错误。 所以我认为这可能是button创build或没有。 而我把懒惰的variables,而不是我创造我的button。

尽pipe如此,作为一个初学者,我真的不知道“layz var”是什么。 我只是知道,导致我的button创build,只有当它被称为。 如果有人在这里启发我和其他初学者关于懒惰的变数,那会很好。 谢谢。

最终解决scheme

 override func viewDidLoad() { super.viewDidLoad() view.addSubview(button) } func exmp(sender: UIButton) { print("hello world") } lazy var 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(self, action: #selector(ButtonViewController.exmp(sender:)), for: .touchDown) return but }()