4

在为 UIButton 定义回调时,我列出了同一操作的多个事件

在目标中,我希望能够区分是什么事件触发了回调

[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
}
4

4 回答 4

8

您可以更改您的操作以获取事件参数,如下所示:

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

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

在回调中添加第二个参数将使 Cocoa 将事件传递给您,以便您可以检查触发回调的原因。

编辑:不幸的是,可可不会向您发送 aUIControlEvent,因此找出导致回调的控制事件并不像检查事件类型那么简单。为UIEvent您提供了一系列触摸,您可以对其进行分析以查看它是否是UITouchPhaseCancelled触摸。但是,这可能不是最方便的处理方式,因此设置多个回调以将正确的类型传递给您可能会更好:

[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
}
于 2013-09-29T10:15:52.287 回答
3

最好执行以下操作:

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

而且当然:

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

-(void)callback2:(UIButton *)button
{
}
于 2013-09-29T10:11:40.107 回答
2

您可以从了解控制事件的第三/第四个方法调用回调:

- (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#>
    }
}
于 2013-09-29T10:14:20.780 回答
1

如果您需要为每个事件提供不同的行为,您应该考虑为每个事件编写不同的回调。

于 2013-09-29T10:10:46.227 回答