2015-06-21 50 views
1

好的,這是一個棘手的問題。當用戶點擊並保持在屏幕上時,我需要提供豐富的警報框。奇怪的點擊並保持在SpriteKit行爲

下面是我用它來做到這一點(在Objective-C SpriteKit)代碼:

在我touchesBegan:withEvent:方法,我有這樣的:

tapBegin = [NSDate date]; 

猜測,使一個NSDate對象與當前日期和時間(Objective-C和Apple相當於DateTime date = Now)。

在我touchesEnded:withEvent:方法,我有這樣的:

NSDate *endTap = [NSDate date]; 
NSDateComponents *comps = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian] components:NSCalendarUnitSecond fromDate:tapBegin toDate:endTap options:0]; 
if (comps.second >= 1) { 
    // tap and hold event 
} else { 
    // normal tap event 
} 

結果應該是這樣的:如果用戶的水龍頭,並擁有一些超過一秒鐘,if的說法應該是true,如果沒有,那麼它應該是false

實際結果有一些奇怪的現象:如果用戶試圖點擊某些東西,他們會隨機獲得點擊並保持事件。我如何解決這個問題?

回答

1

如果你想獲得兩個日期之間的區別,那麼你應該改爲使用timeIntervalSinceDate: 我會改變touchesEnded:withEvent:以下幾點:

NSDate *endTap = [NSDate date]; 
NSTimeInterval diff = [tapBegin timeIntervalSinceDate:endTap]; 
NSTimeInterval threshold = 1.0; 
if (diff >= threshold) { 
    // tap and hold event 
} else { 
    // normal tap event 
}