2012-04-19 75 views
0

我一直在尝试实现一个按钮与两个不同的触摸事件。比方说,当用户点击按钮(触摸很短的时间),它会触发actionTapped,当用户长时间触摸按钮时会触发actionTouched。一个按钮与两个不同的触摸事件

This link可能会给出一个想法,但它会使动作重复一遍又一遍。

+0

检查此[http://stackoverflow.com/questions/4013896/detecting-long-tap-on-iphone](http://stackoverflow.com/ questions/4013896/detected-long-tap-on-iphone) – 2012-04-19 12:35:06

回答

0

好的,这是我的解决方案。 scheduledTimerWithTimeInterval是最小间隔,使得它触及:

- (IBAction) micButtonTouchedDownAction { 
    self.micButtonTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(micButtonAction:) userInfo:nil repeats:YES]; 
    self.micButtonReleased = FALSE; 
} 

- (IBAction) micButtonTouchedUpInsideAction { 
    self.micButtonReleased = TRUE; 
} 

- (IBAction) micButtonTouchedUpOutsideAction { 
    self.micButtonReleased = TRUE; 
} 

- (void) micButtonAction:(NSTimer *)timer { 
    [self.micButtonTimer invalidate]; 
    self.micButtonTimer = nil; 

    if(self.micButtonReleased) { 
     NSLog(@"Tapped"); 
    } 
    else { 
     NSLog(@"Touched"); 
    } 
} 
1

你会想在touchDown事件上设置一个定时器,它将执行你的longPress函数。在touchUp事件中,您可以取消定时器。真的很简单。

+0

这是一个好主意,但区分这两个事件又怎么样? – giorashc 2012-04-19 12:38:59

+0

在设置定时器之前,可以在touchDown事件中执行初始(短按)代码。长按代码可以在计时器事件中执行。 – cdstamper 2012-04-19 12:41:12

+1

,但您仍然可以同时执行两项操作(如果定时器关闭...) – giorashc 2012-04-19 12:42:34

0

我将做到以下几点:

  1. 在您触摸向下的方法:存储当前时间(可以称之为touchDownTime)。
  2. 在你触摸了方法:计算time elapsed = current time - touchDownTime

    2.1转换为秒

    2.2如果时间流逝>需要时间做动作1(长按),做别的动作2(短触摸)

1

iOS SDK包含两个适合您需求的手势识别器:

  • UIT apGestureRecognizer
  • UILongPressGestureRecognizer

没有任何动作附加到其创建您的按钮。然后创建两个手势识别器,每个类型中的一个,每个都映射到您想要的动作。然后将手势识别器附加到按钮上。

相关问题