Iphone – How to implement target-action-mechanism for custom control

cocoa-touchiphoneuikit

I'm going to write my own custom control that is very different from UIButton. It's so much different that I decided to write it from scratch. So all I subclass is UIControl.

When my control is touched up inside, then I want to fire a message in means of target-action. The user of that class may instantiate it and then add some targets and actions for this event.

i.e. imagine I would call internally a method -fireTargetsForTouchUpEvent. How could I maintain this target-action-mechanism in my class? Do I have to add all targets and actions to my own array and then just call selectors (the actions) on the target objects in a for-loop? Or is there a more intelligent way to do it?

I imagine to provide some methods for adding targets and actions for some events like that touch up event (I raise that manually by calling a internal method when that happens). Any idea?

Best Answer

I just want to clarify what @Felixyz said because it wasn't clear to me at first.

If you are subclassing UIControl, even if you are going to have a custom event, you don't have to keep track of your own targets/actions. The functionality is already there, all you have to do is call the code below in your subclass to trigger the event:

[self sendActionsForControlEvents:UIControlEventValueChanged];

Then in the view or view controller that instantiates your custom UIControl, just do

[customControl addTarget:self action:@selector(whatever) forControlEvents:UIControlEventValueChanged];

For custom event, just define your own enum (for example, UIControlEventValueChanged is equal to 1 << 12). Just make sure it is within the permitted range defined by UIControlEventApplicationReserved