2011-01-28 8 views

答えて

3

はい可能です。これは非常に簡単です。

タッチが開始されると現在の時間([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); 
} 
1

感謝を助言を与えるので、同じよう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に覚えています。

3

上記と少し異なる回答です。 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); 
    } 
} 
関連する問題