How to distinguish between fired events for a UIBu

2019-05-14 22:00发布

问题:

When defining a callback for a UIButton I listed several events for the same action

In the target I would like to be able to distinguish what event triggered the callback

[button addTarget:self action:@selector(callback:) forControlEvents:UIControlEventTouchDown | UIControlEventTouchCancel];

-(void)callback:(UIButton *)button
{
  // need to be able to distinguish between the events
if (event == canceled)
{
}
if (event == touchDown)
{
}
... etc
}

回答1:

You can change your action to take the event parameter, like this:

[button addTarget:self action:@selector(callback:event:) forControlEvents:UIControlEventTouchDown | UIControlEventTouchCancel];

-(void)callback:(UIButton *)button (UIEvent*)event {
    ...
}

Adding a second parameter to your callback will make Cocoa pass the event to you, so that you could check what has triggered the callback.

EDIT : Unfortunately, cocoa does not send you a UIControlEvent, so figuring out what control event has caused the callback is not as simple as checking the event type. The UIEvent provides you a collection of touches, which you can analyze to see if it's a UITouchPhaseCancelled touch. This may not be the most expedient way of doing things, though, so setting up multiple callbacks that channel the correct type to you may work better:

[button addTarget:self action:@selector(callbackDown:) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(callbackCancel:) forControlEvents:UIControlEventTouchCancel];

-(void)callbackDown:(UIButton*) btn {
    [self callback:btn event:UIControlEventTouchDown];
}
-(void)callbackCancel:(UIButton*) btn {
    [self callback:btn event:UIControlEventTouchCancel];
}
-(void)callback:(UIButton*)btn event:(UIControlEvent) event {
    // Your actual callback
}


回答2:

Better to do the below:

[button addTarget:self action:@selector(callback1) forControlEvents:UIControlEventTouchDown];
[button addTarget:self action:@selector(callback2) forControlEvents:UIControlEventTouchCancel];

And of course:

-(void)callback1:(UIButton *)button
{
}

-(void)callback2:(UIButton *)button
{
}


回答3:

You could call the callback from a third / fourth method that knows about the control Event:

- (void)buttonTouchDown:(UIButton*)button {
    [self callback:(UIButton*)button forControlEvent:UIControlEventTouchDown];
}


- (void)buttonTouchCancel:(UIButton*)button {
    [self callback:(UIButton*)button forControlEvent:UIControlEventTouchCancel];
}

-(void)callback:(UIButton *)button forControlEvent:(UIControlEvents)controlEvents {
    if (controlEvents == UIControlEventTouchDown) {
       <#do something#>
    }
    if (controlEvents == UIControlEventTouchCancel) {
       <#do something#>
    }
}


回答4:

If you need different behaviors for each event, you should consider writing a different callback for each one.