2
votes

Why isn't this working:

    self.backButton?.addTarget(self, action: Selector("backButtonPressed:"), forControlEvents: .TouchUpInside)

   // unrecognized selector sent to instance CRASH
    func backButtonPressed(sender:AnyObject?) {

    }

this crash to (unrecognized selector sent to instance)

  func backButtonPressed(sender:UIButton) {

    }
3
Works for me actually, without any modifications. - rshev
I tried with both function and they both crash. The message: -[MyApp.HeaderView backButtonPressed:]: unrecognized selector sent to instance 0x7f9bd8432c70 - BlackMouse

3 Answers

6
votes

If I am not wrong you have declared your backButtonPressed method inside another method like this:

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(frame: CGRectMake(150, 240, 75, 30))
    button.setTitle("Next", forState: UIControlState.Normal)
    button.addTarget(self, action: Selector("backButtonPressed:"), forControlEvents: UIControlEvents.TouchUpInside)
    button.backgroundColor = UIColor.greenColor()
    self.view.addSubview(button)

    func backButtonPressed(sender:AnyObject?) {

        print("Called")
    }
    // Do any additional setup after loading the view, typically from a nib.
}

This is wrong way.

Declare your method outside as shown in below code:

override func viewDidLoad() {
    super.viewDidLoad()

    let button = UIButton(frame: CGRectMake(150, 240, 75, 30))
    button.setTitle("Next", forState: UIControlState.Normal)
    button.addTarget(self, action: Selector("backButtonPressed:"), forControlEvents: UIControlEvents.TouchUpInside)
    button.backgroundColor = UIColor.greenColor()
    self.view.addSubview(button)
}

func backButtonPressed(sender:AnyObject?) {

    print("Called")
}
1
votes

on swift you dont need to write selector anymore just

self.backButton?.addTarget(self, action: "backButtonPressed:", forControlEvents: .TouchUpInside)
0
votes

Replace your action argument - selector like:

self.backButton?.addTarget(self, action: #selector(self. backButtonPressed(sender:)), for:. touchUpInside)

Since Swift 3, selector syntax has been changed as shown here.

The use of string literals for selector name is error-prone: there is no checking that the string is even a well-formed selector, much less that it refers to any known method, or a method of the intended class. Moreover, with the effort to perform automatic renaming of Objective-C APIs, the link between Swift name and Objective-C selector is non-obvious. By providing explicit "create a selector" syntax based on the Swift name of a method, we eliminate the need for developers to reason about the actual Objective-C selectors being used.