私はタッチの開始とタッチ終了のイベントの間の時間を知りたい1つのiphoneゲームアプリケーションを実装しています。touchesBeganとiphoneのtouchendイベントの間の時間を見つける方法は?
それは可能ですか?
、私にあなたのヘッダーには、事前
私はタッチの開始とタッチ終了のイベントの間の時間を知りたい1つのiphoneゲームアプリケーションを実装しています。touchesBeganとiphoneのtouchendイベントの間の時間を見つける方法は?
それは可能ですか?
、私にあなたのヘッダーには、事前
はい可能です。これは非常に簡単です。
タッチが開始されると現在の時間([NSDate date])を保存し、タッチが終了した現在の時間と保存された開始時間の差を取得します。
@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);
}
で
感謝を助言を与えるので、同じようNSDateプロパティを作成してください:touchesBegan
方法では、次に
@property(nonatomic, retain) NSDate *touchesBeganDate;
、この操作を行います。
をself.touchesBeganDate = [NSDate date];
最後に、touchEnd
の方法では:
NSDate *touchesEndDate = [NSDate date];
NSTimeInterval touchDuration = [touchesEndDate timeIntervalSinceDate:
self.touchesBeganDate];
self.touchesBeganDate = nil;
NSTimeIntervalは、通常のfloat変数として使用できます。
ハッピーコーディング:)
はそうそう、@synthesize
touchesBeganDate
に覚えています。
上記と少し異なる回答です。 NSDateから現在時刻を取得するのではなく、UITouchオブジェクトのtimestamp propertyを使用してください。これはNSDateオブジェクトではなく、NSTimeInterval(つまり、Cの整数型)です。したがって、たとえば
// 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);
}
}