Added from comments on another answer: func action() is not just a poor choice for a function name and action, it fails to build. (You can use it as an input function parameter though, which I do for clarity when passing in target/action to an init() that sets these things.) I'm replacing this with MyAction() for clarity.
Try this:
self.addTarget(self, action: #selector(MyAction), for: .touchUpInside)
The said, a much better design is to move the MyAction() function to the button superview, as that makes things more aligned with basic MVC design:
Superview:
let myButton = ActionButton()
// include other button setup here
myButton.addTarget(self, action: #selector(MyAction), for: .touchUpInside
func action(_ sender: ActionButton) {
// code against button tap here
}
Alternative coding for this, keeping the "action()" method in the view controller but moving only the "addTarget" into the button:
self.addTarget(superview?, action(superview?.MyAction), for: .touchUpInside)
Why am I asking you to consider moving the "MyAction()" method to the superview? Twofold:
- It controls not only the button, but all other subviews in it's view and they commonly interact with each other via the view controller.
- It makes the button much more reusable in other scenarios.