skip to Main Content

I have a function for creating a custom button in my Swift project where I pass an objc function selector name but the code crashes when I click on the button. Can anyone pin point why my code is crashing? I get the error message:
Unrecognized selector +[TwitterTutorial.Utilities handleDontHaveAnAccountButtonClicked]

Here is my custom button function:

class Utilities {

    static func createCustomButton(withFirstPart first: String, andSecondPart second: String, andSelector selector: Selector) -> UIButton {
        let button = UIButton(type: .system)
        
        let attributedTitle = NSMutableAttributedString(string: first,
                                                        attributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16),
                                                                     NSAttributedString.Key.foregroundColor: UIColor.white])
        attributedTitle.append(NSAttributedString(string: second,
                                                  attributes: [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 16),
                                                               NSAttributedString.Key.foregroundColor: UIColor.white]))
        
        button.setAttributedTitle(attributedTitle, for: .normal)
        
        button.addTarget(self, action: selector, for: .touchUpInside)

        return button
    }
}

and here is a call to the function to create the button:

    private let dontHaveAccountButton = Utilities.createCustomButton(withFirstPart: "Don't have an account? ",
                                                                     andSecondPart: "Sign Up",
                                                                     andSelector: #selector(handleDontHaveAnAccountButtonClicked))

    @objc func handleDontHaveAnAccountButtonClicked() {
        print("DEBUG: Don't have an account button clicked")
    }

I have noticed that it works when I remove the static keyword from the class method declaration but I would like to use static methods in my class Utilities.

2

Answers


  1. You set the target to self that means the selector method must be declared in Utilities.

    Possible solutions are

    • Add a parameter target to the method.
    • Extend UIButton.
    • Extend UIViewController or the type the button is created in.
    • Declare the selector method in Utilities (doesn’t make much sense).
    Login or Signup to reply.
  2. You are using a static function to create the button, and when calling

    button.addTarget(self, action: selector, for: .touchUpInside)
    

    the self refers to the class Utilities not an instance.

    Therefore, the selector should also refer to a class (e.g. static) function, like

    @objc static func handleDontHaveAnAccountButtonClicked() {
        print("DEBUG: Don't have an account button clicked")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search