开发者

how to find time between touchesBegan and touchend event in iphone?

I am implementing one iphone game application in which I want to find out time between touch begin and touch end event.

Is it possible?

Please give me advice

Thanks in advance开发者_StackOverflow社区


Yes this is possible. And this is very very easy.

You save the current time (i.e. [NSDate date]) when the touch starts, and get the difference between the current time when the touch ends and the saved start time.

@interface MyViewController : UIViewController {
    NSDate *startDate;
}
@property (nonatomic, copy) NSDate *startDate;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    self.startDate = [NSDate date];

}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    NSTimeInterval ti = [[NSDate date] timeIntervalSinceDate:self.startDate];
    NSLog(@"Time: %f", ti);
}


A slightly different answer to those above; use the timestamp property on the UITouch object rather than getting the current time from NSDate. It's an NSTimeInterval (ie, a C integral type) rather than an NSDate object. So, e.g.

// include an NSTimeInterval member variable in your class definition
@interface ...your class...
{
    NSTimeInterval timeStampAtTouchesBegan;
}

// use it to store timestamp at touches began
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *interestingTouch = [touches anyObject]; // or whatever you do
    timeStampAtTouchesBegan = interestingTouch.timestamp // assuming no getter/setter
}

// and use simple arithmetic at touches ended
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    if([touches containsObject:theTouchYouAreTracking])
    {
        NSLog(@"That was a fun %0.2f seconds", theTouchYouAreTracking.timestamp - timeStampAtTouchesBegan);
    }
}


In your header, make an NSDate property like so:

@property(nonatomic, retain) NSDate *touchesBeganDate;

Then, in the touchesBegan method, do this:

self.touchesBeganDate = [NSDate date];

And finally, in the touchEnd method:

NSDate *touchesEndDate = [NSDate date];
NSTimeInterval touchDuration = [touchesEndDate timeIntervalSinceDate:
self.touchesBeganDate];
self.touchesBeganDate = nil;

That NSTimeInterval can be used as a normal float variable.

Happy coding :)

Oh yeah, remember to @synthesize the touchesBeganDate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜