I am creating a Swift project and I want to define a specific protocol that enforces other components to implement a animate
method:
protocol AnimatableBehavior {
@IBAction func animate()
}
The problem is I want this method to be an 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 have considered:
- Remove
@IBAction
, but then I need to remember adding it in every class that implements. Not very elegant and error prone. - Create a base class instead of protocol, but then I am enforcing all components to subclass my base class instead of their own choice ones, so it is not a valid option.
Any other ideas?
EDIT: Response to comments below.
The idea of the IBAction
on the protocol is because in the project there will be many different devs implementing small UI components, all of which have the animate method. The components can be added programatically or by Interface Builder and it is very convenient that they are always IBAction
because I plan to compose them from IB files to simplify the View Controllers to the maximum extent (and this is clearly a View only task).
Therefore, the solution proposed below of adding a method in the controller that just calls the animate
of the component is not good because it is redundant code and makes your Controller more dependent on your View.
The idea of letting the dev to remember adding the IBAction
keyword on the method is workable, but as I said it is error prone (and by that I mean that there will be some forgetting about it), and I want to make sure that this is always accessible from IB. It also adds extra cognitive load, because I will need to document this lack of IBAction
on the protocol and request the implementor to add it manually.
I know is not the common way of working in iOS and UIKit
, but that was why I posted the question, maybe someone has an alternative idea.