2013-04-02 46 views
-1

我想执行一个方法-recognized-touchesEnded方法执行完成后2秒钟。但是,如果用户在这2秒钟内触摸了某些东西,则不能执行该方法。在下次再次执行方法后,必须再次设置计时器以等待2秒钟。等等...希望这个问题很清楚。如果没有,请让我知道。执行延迟后的方法

回答

2

您需要使用NSTimer来协调这一点。当您要启动计时器的事件触发时,请使用scheduledTimerWithTimeInterval:target:selector:userInfo:repeats:在两秒钟内安排函数调用。

使用视图控制器全局的布尔变量来防止定时器置于其间。

这是一个粗略的想法:

BOOL shouldRespondToTouch = YES; 

- (void)touchesEnded { 
    [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(doAction) userInfo:nil repeats:NO]; 
    shouldRespondToTouch = NO; 
} 

- (void)doAction { 
    shouldRespondToTouch = YES; 
    // Do stuff here 
} 
+0

谢谢@woz,+1。但是,我发现了一个可能更好的方法。 – m177312

0
-(void) touchesEnded { 
    [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(targetMethod:) userInfo:nil repeats: YES]; 

    } 

    //define the targetmethod 
    -(void) targetMethod: NSTimer * theTimer 
{ 
    NSLog(@\"Me is here at 1 minute delay\"); 
    } 
0

事实证明,这是非常简单的。

在view.h

NSDate *startDate; 

创建一个实例变量添加以下这些方法在view.m

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { 
self->startDate = [NSDate date]; 
NSLog(@"%@", startDate); 
} 

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { 
if (self->startDate) { 
     NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self->startDate]; 
     NSLog(@"Time: %f", ti); 
     if (ti >= 2) { 
      NSLog(@"Yes, greater than 2 seconds !"); 
     } 
    } 
} 

就像一个魅力。