[IOS]實現IOS單擊或者雙擊事件

提供一下三種方法參考:

方法一:

  1. //單擊事件  
  2. -(void)fun1  
  3. {  
  4.       
  5.     NSLog(@"click1");  
  6. }  
  7. //雙擊事件  
  8. -(void)fun2  
  9. {  
  10.     NSLog(@"click2");  
  11. }  
  12.   
  13. //單擊和雙擊方法之一  
  14. -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
  15. {  
  16.       
  17.     if ([[touches anyObject] tapCount] == 1) {  
  18.         [self performSelector:@selector(fun1) withObject:nil afterDelay:1];  
  19.     }  
  20.     else if ([[touches anyObject] tapCount] ==2)  
  21.     {  
  22.         [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(fun1) object:nil];  
  23.         [self performSelector:@selector(fun2) withObject:nil afterDelay:1];  
  24.     }  
  25. }  

方法二:[線程]

  1. int num = 0;  
  2. -(void)fun1  
  3. {  
  4.     [NSThread sleepForTimeInterval:1];  
  5.     if(num == 1)  
  6.     {  
  7.         NSLog(@"click 1");  
  8.     }  
  9. }  
  10. -(void)fun2  
  11. {  
  12.     [NSThread sleepForTimeInterval:1];  
  13.     if(num == 2)  
  14.     {  
  15.         NSLog(@"click 2");  
  16.     }  
  17. }  
  18. -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event  
  19. {  
  20.     if([[touches anyObject] tapCount] == 1)  
  21.     {  
  22.         num = 1;  
  23.         NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(fun1) object:nil];  
  24.         [thread start];  
  25.     }  
  26.     else if([[touches anyObject] tapCount] == 2)  
  27.     {  
  28.         num = 2;  
  29.         NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(fun2) object:nil];  
  30.         [thread start];  
  31.     }  
  32. }  

方法三:[利用手勢控件本身自帶的方法]

原理:執行第二個方法的時候,取消第一次的方法操作

  1. - (void)viewDidLoad  
  2. {  
  3.     [super viewDidLoad];     
  4.  //點擊事件  
  5.     UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fun1)];  
  6.     //單點觸摸  
  7.       tap.numberOfTouchesRequired = 1;  
  8.     //點擊幾次,如果是1就是單擊  
  9.     tap.numberOfTapsRequired = 1;  
  10.     [self.view addGestureRecognizer:tap];  
  11.       
  12.     UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(fun2)];  
  13.     tap2.numberOfTapsRequired = 2;  
  14.     [self.view addGestureRecognizer:tap2];  
  15.       
  16.     //如果滿足第二次 第一次的就取消  
  17.     [tap requireGestureRecognizerToFail:tap2];  
  18. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章