如何区分UIButton回调操作的触发事件
在为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 }
您可以更改操作以采用事件参数,如下所示:
[button addTarget:self action:@selector(callback:event:) forControlEvents:UIControlEventTouchDown | UIControlEventTouchCancel]; -(void)callback:(UIButton *)button (UIEvent*)event { ... }
向回调添加第二个参数将使Cocoa将事件传递给您,以便您可以检查触发回调的内容。
编辑:不幸的是,cocoa 没有向您发送UIControlEvent
,因此找出导致回调的控件事件并不像检查事件类型那么简单。 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 }
最好做到以下几点:
[button addTarget:self action:@selector(callback1) forControlEvents:UIControlEventTouchDown]; [button addTarget:self action:@selector(callback2) forControlEvents:UIControlEventTouchCancel];
而且当然:
-(void)callback1:(UIButton *)button { } -(void)callback2:(UIButton *)button { }
您可以从知道控件事件的第三个/第四个方法调用回调:
- (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#> } }
如果每个事件需要不同的行为,则应考虑为每个事件编写不同的回调。