我正在实施一个iphone游戏应用程序,我想在其中找出触摸开始和触摸结束事件之间的时间。
有可能吗?
请给我建议
提前致谢
答案 0 :(得分:3)
是的,这是可能的。这非常容易。
您可以在触摸开始时保存当前时间(即[NSDate日期]),并获取触摸结束时的当前时间与保存的开始时间之间的差异。
@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);
}
答案 1 :(得分:3)
对上述答案略有不同;使用UITouch对象上的timestamp property而不是从NSDate获取当前时间。它是NSTimeInterval(即C积分类型)而不是NSDate对象。所以,例如。
// 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);
}
}
答案 2 :(得分:1)
在标题中,创建一个NSDate属性,如下所示:
@property(nonatomic, retain) NSDate *touchesBeganDate;
然后,在touchesBegan
方法中,执行以下操作:
self.touchesBeganDate = [NSDate date];
最后,在touchEnd
方法中:
NSDate *touchesEndDate = [NSDate date];
NSTimeInterval touchDuration = [touchesEndDate timeIntervalSinceDate:
self.touchesBeganDate];
self.touchesBeganDate = nil;
NSTimeInterval可以用作普通的浮点变量。
快乐编码:)
哦,是的,记得@synthesize
touchesBeganDate
。