优雅的方式实现按下并保持连续事件发射?

时间:2012-11-06 10:18:16

标签: objective-c ios xcode

由于按住按钮,我经常需要触发一系列事件。想象一个+按钮增加一个字段:点击它会使它增加1,但点击&保持应该说每秒递增1,直到按钮被释放。另一个例子是按住音频播放器类型应用程序中的向后或向前按钮时的擦洗功能。

我通常采用以下策略:

  1. touchDownInside我按照我想要的间隔设置了一个重复计时器。
  2. touchUpInside我无效并释放定时器。
  3. 但是对于每个这样的按钮,我需要一个单独的计时器实例变量,2个目标动作和2个方法实现。 (这假设我正在编写一个通用类,并且不希望对同时触摸的最大数量施加限制。)

    有没有一种更优雅的方法可以解决这个问题,我错过了?

2 个答案:

答案 0 :(得分:2)

通过以下方式为每个按钮注册事件:

[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);
}

答案 1 :(得分: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来识别用户点按。

希望这会有所帮助。 :)