2012-11-06 40 views
5

由于按下按钮,我经常需要触发一系列事件。想想一个+按钮,增加一个字段:点击它应该增加1,但点击&保持应该说每秒增加1,直到按钮被释放。另一个例子是在音频播放器类型的应用程序中按住向后或向前按钮时的清理功能。实现按住持续事件触发的优雅方式?

我通常采取以下策略:

  1. touchDownInside我设置了我想要的间隔重复的计时器。
  2. touchUpInside我无效并释放计时器。

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

有没有更优雅的方式来解决这个问题,我错过了?

+2

'UILongPressGestureRecognizer'与从属的'UITapGestureRecognizer'。就这些。 –

+0

重复:http://stackoverflow.com/questions/9971241/ios-press-and-hold-gesture-tap –

回答

1

通过注册,每个按钮的事件:

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

对于每一个按钮,设置tag属性:

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

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

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

我建议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识别用户的水龙头。

希望这会有所帮助。 :)

相关问题