Can you make custom events with UIControlEventAppl

2020-06-03 08:57发布

问题:

I have written a subclass of UIControl that tracks a number of gestures that are of interest to me. In the documentation for the UIControlEvents enumeration, it says that there is a range of event numbers called UIControlEventApplicationReserved that is "available for application use." Does this mean that I am free to use this range of numbers for my own custom events?

If so, can someone please tell me how to fire events? The obvious way I can think of to do it is this:

enum {
     ...
     MyCustomEvent = 65,
     ...
};

...

UIEvent* customEvent;

...

for (id target in [self allTargets])
{
     for (NSString* action in [self actionsForTarget:target forControlEvent:MyCustomEvent])
     {
          [self sendAction:NSSelectorFromString(action) to:target forEvent:customEvent];
     }
}

Would that even work?

回答1:

Okay, this is an old subject but I'm going to add my answer to this. I can't really tell for sure whether you can use this mask for your own application even though I suspect it.

But I can tell you for sure how to use it. For starter this value masks the bits at position 24, 25, 26 and 27. You should write an enum of your own that uses this bits only, for example:

enum {
    MyPrimaryActionEvent = 1 << 24,
    MySecondaryActionEvent = 1 << 25,
};

Once that is done you can register for these actions:

[myButton addTarget:self action:@selector(someAction:) forControlEvents: MyPrimaryActionEvent];

Every time the action MyPrimaryActionEvent is triggered, self will receive the message someAction:. Now how to trigger that action is up to the button itself. In your own UIControl subclass you can trigger the change as follow:

[self sendActionsForControlEvents:MyPrimaryActionEvent];

This will send all the actions to all the targets registered for MyPrimaryActionEvent event. And you're done.