2011-01-28 16 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屬性,像這樣:

@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可用作普通浮點型變量。

編碼愉快:)

噢,記得@synthesizetouchesBeganDate

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); 
    } 
} 
相關問題