如何区分 UIButton 回调操作的触发事件 [英] How to distinguish between fired events for a UIButton callback action
问题描述
在为 UIButton 定义回调时,我为同一操作列出了多个事件
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 {
...
}
向回调添加第二个参数将使 Cocoa 将事件传递给您,以便您可以检查是什么触发了回调.
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.
不幸的是,可可不会向您发送UIControlEvent
,所以搞清楚是什么控制事件导致了回调并不像检查事件类型那么简单.UIEvent
为您提供了一系列触摸,您可以对其进行分析以查看它是否是 UITouchPhaseCancelled
触摸.不过,这可能不是最方便的做事方式,因此设置多个回调以将正确的类型引导给您可能会更好:
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
}
这篇关于如何区分 UIButton 回调操作的触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!