snapchatdotcom snapchatdotcom - 3 months ago 7
Swift Question

addTarget to UIButton programmatically gives me 'unrecognized selector sent to class'

I'm trying to learn how to create button target actions, however, when I press the button, I get those LLDB errors and I get told that it was an 'unrecognized selector sent to class'.

Where am I going wrong here?


let phoneIcon: UIButton = {
let iv = UIImageView()

iv.translatesAutoresizingMaskIntoConstraints = false
iv.image = UIImage(named: "Phone3")?.imageWithRenderingMode(.AlwaysTemplate)

let phoneBtn = UIButton(type: .Custom)

phoneBtn.addTarget(CallButton.self, action: #selector(CallButton.buttonPressed(_:)), forControlEvents: .TouchDown)
phoneBtn.addTarget(CallButton.self, action: #selector(CallButton.buttonReleased(_:)), forControlEvents: .TouchUpInside)

phoneBtn.translatesAutoresizingMaskIntoConstraints = false
phoneBtn.setImage(iv.image!, forState: .Normal)
phoneBtn.tintColor = UIColor(r: 224, g: 224, b: 224)

return phoneBtn


Here's the CallButton class where I call for buttonPressed and buttonReleased.

class CallButton: UIControl {

func buttonPressed(sender: AnyObject?) {
func buttonReleased(sender: AnyObject?) {
print("Let go")



You are setting the class itself, not an instance, as the target of the action.

Therefore, the method you set as the action should be implemented as a class method, not an instance method:

class func buttonPressed(sender: AnyObject?) {