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
You set the
target
toself
that means the selector method must be declared inUtilities
.Possible solutions are
target
to the method.UIButton
.UIViewController
or the type the button is created in.Utilities
(doesn’t make much sense).You are using a static function to create the button, and when calling
the
self
refers to the classUtilities
not an instance.Therefore, the selector should also refer to a class (e.g. static) function, like