Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unrecognized selector sent to class

Tags:

ios

swift

swift3

I've seen that, this is a common issue but i couldn't find any solution for myself.

Here is the code:

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.

Any help is appreciated! Thanks.

like image 999
Unal Celik Avatar asked Oct 18 '25 02:10

Unal Celik


1 Answers

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)

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).

like image 117
vacawama Avatar answered Oct 19 '25 17:10

vacawama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!