Search code examples
iosswiftunrecognized-selector

Assigning a selector passed to a method as a button target action


So here is my scenario. I'm making a toast view. The toast view accepts a selector which it sets as the target action of a button inside the toast view. But i get the unrecognised selector error.

 // MainViewController.swift

 func viewDidLoad() {

     // Custom initializer for toastview
     let toastView = ToastView(view: nil, selector: #selector(testSelector))
     .
     .
     .
 }

 @objc func testSelector() {
      print("Test")
 }

 // ToastView.swift

 var selector: Selector

 convenience init(view: UIView, selector: Selector) {
      self.selector = selector
      let button = UIButton(type: .system)
      button.addTarget(self, action: self.selector, for: .touchUpInside)
 }

Edit: Changed the code a bit to reflect what is actually in my original code.


Solution

  • You got the target wrong. Target must be an object of class where your selector (method or function) is defined. If function is defined in your MainViewController target must be an object of MainViewController. Same if function is defined in ToastView selector must be an object of ToastView.

    Either you move your testSelector function in your ToastView class and keep rest the same.

    Option 1

    // something like this 
    class ToastView {
        @objc func testSelector() {
            print("Test")
        } 
    }
    

    Option 2

    Or you pass target as init paramater.

    // ToastView.swift
    convenience init(view: UIView, target:Any, selector: Selector) {
        let button = UIButton(type: .system)
        button.addTarget(target, action: selector, for: .touchUpInside)
    }
    

    And In your MainViewController call it like this.

    func viewDidLoad() {
    
       // Custom initializer for toastview
       let toastView = ToastView(view: nil, target:self, selector: #selector(testSelector))
        .
        .
        .
    }