UIControl: sendActionsForControlEvents omits UIEvent

二次信任 提交于 2019-11-28 01:35:11

问题


I want to implement a custom subclass of UIControl. It works beautifully except for one fatal problem that is making me spit teeth. Whenever I use sendActionsForControlEvents: to send an action message out, it omits to include a UIEvent. For example, if I link it to a method with the following signature:

- (IBAction) controlTouched:(id)sender withEvent:(UIEvent *)event

... the event always comes back as nil! The problem seems to occur within sendActionsForControlEvents:

Now, I need my IBAction to be able to determine the location of the touch. I usually do so by extracting the touches from the event. Surely there must be some way to ensure that the correct event is delivered? It's a pretty fundamental part of using a UIControl!

Anyone know a legal workaround?


回答1:


I would assume that this is because the sendActionsForControlEvents: method can't know which UIEvent (if any) your control event should be associated with.

You could try to send all the actions separately (replicating what the sendActionsForControlEvents: method does, according to the documentation), so you can specifically associate them with a UIEvent:

UIEvent *event = ...;
UIControlEvents controlEvent = ...;

for (id target in [self allTargets]) {
    NSArray *actions = [self actionsForTarget:target forControlEvent:controlEvent];
    for (NSString *action in actions) {
        [self sendAction:NSSelectorFromString(action) to:target forEvent:event];
    }
}



回答2:


I have ONE possible solution at the moment, but I'm not very happy about it. For others faced with the same problem though, here it is. First, declare a local variable or property for a UIEvent thus:

@property (nonatomic, assign) UIEvent * currentEvent;

Now, in your touch-handling routines, set that local variable to the current UIEvent for that routine before calling [self sendActionsForControlEvents:] like so, replacing UIControlEventTouchDown with whichever action you want to send out of course.

self.currentEvent = event;
[self sendActionsForControlEvents: UIControlEventTouchDown];

Finally, override the following method thus:

- (void) sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event
{
    [super sendAction:action to:target forEvent:self.currentEvent];
}

This works, but I am not in the least bit fond of it, so if anybody has an alternative solution that doesn't rely on holding a weak reference to a UIEvent, I will be overjoyed to hear it!



来源:https://stackoverflow.com/questions/11382816/uicontrol-sendactionsforcontrolevents-omits-uievent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!