문제

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
}
도움이 되었습니까?

해결책

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
}

다른 팁

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
{
}

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#>
    }
}

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top