在为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
}
答案 0 :(得分:7)
您可以更改操作以采用事件参数,如下所示:
[button addTarget:self action:@selector(callback:event:) forControlEvents:UIControlEventTouchDown | UIControlEventTouchCancel];
-(void)callback:(UIButton *)button (UIEvent*)event {
...
}
向回调添加第二个参数将使Cocoa将事件传递给您,以便您可以检查触发回调的内容。
编辑:不幸的是,cocoa does not send you a 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
}
答案 1 :(得分: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
{
}
答案 2 :(得分: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#>
}
}
答案 3 :(得分:1)
如果每个事件需要不同的行为,则应考虑为每个事件编写不同的回调。