Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish between fired events for a UIButton callback action

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
}
like image 990
Avner Barr Avatar asked Dec 09 '22 12:12

Avner Barr


2 Answers

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
}
like image 181
Sergey Kalinichenko Avatar answered Dec 11 '22 10:12

Sergey Kalinichenko


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
{
}
like image 27
Tarek Hallak Avatar answered Dec 11 '22 09:12

Tarek Hallak