优雅的方式来执行按住持续事件触发?

由于按下button,我经常需要触发一系列事件。 想想一个增加一个字段的+button:点击它应该增加1,但点击并按住应该说增加1每秒,直到button被释放。 另一个例子是在audio播放器types的应用程序中按住向后或向前button时的清理function。

我通常采取以下策略:

  1. touchDownInside我设置了一个重复计时器与我所需的时间间隔。
  2. touchUpInside我无效和释放计时器。

但是对于每个这样的button,我需要一个单独的计时器实例variables,以及2个目标操作和2个方法实现。 (这是假设我正在写一个generics类,并不想对同时触摸的最大数量施加限制)。

有没有更优雅的方式来解决这个我失踪?

我build议UILongPressGestureRecognizer

 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(addOpenInService:)]; longPress.delegate = self; longPress.minimumPressDuration = 0.7; [aView addGestureRecognizer:longPress]; [longPress release]; longPress = nil; 

在发射事件,你可以打电话

 - (void) addOpenInService: (UILongPressGestureRecognizer *) objRecognizer { // Do Something } 

同样,您可以使用UITapGestureRecognizer来识别用户的水龙头。

希望这可以帮助。 🙂

通过以下方式注册每个button的事件:

 [button addTarget:self action:@selector(touchDown:withEvent:) forControlEvents:UIControlEventTouchDown]; [button addTarget:self action:@selector(touchUpInside:withEvent:) forControlEvents:UIControlEventTouchUpInside]; 

对于每个button,请设置tag属性:

 button.tag = 1; // 2, 3, 4 ... etc 

在处理程序中,做任何你需要的。 通过标签识别button:

 - (IBAction) touchDown:(Button *)button withEvent:(UIEvent *) event { NSLog("%d", button.tag); }