I am creating a Swift project, and I want to define a specific protocol that uses other components to implement the animate method:
protocol AnimatableBehavior { @IBAction func animate() }
The problem is that I want this method to be IBAction , but I get this error from Xcode:
Only instance methods can be declared "IBAction"
My question is: how would you implement such a thing?
I reviewed:
- Remove
@IBAction , but then I need to remember adding it to every class that implements. Not very elegant and error prone. - Create a base class instead of a protocol, but then I use all the components to subclass my base class instead of my own, so it is not a valid option.
Any other ideas?
EDIT: response to comments below.
The idea of IBAction in the protocol is that the project will have many different developers implementing small components of the user interface, all of which have an animation method. Components can be added programmatically or using Interface Builder , and it’s very convenient that they are always IBAction , because I plan to compile them from IB files to simplify View Viewers to the maximum extent (and this is clearly a viewing-only task).
Therefore, the solution proposed below to add a method to a controller that simply calls the animate component is not good, because it is redundant code and makes your controller more dependent on your presentation.
The idea of letting the developer remember to add the IBAction keyword in the method is workable, but, as I said, this is error prone (and I mean that some will forget about it), and I want to make sure that it is always available from IB. It also adds extra cognitive load because I will need to document this IBAction flaw in the protocol and ask the developer to add it manually.
I know that this is not the usual way of working in iOS and UIKit , but that is why I posted the question, maybe someone has an alternative idea.