如果用户点击1次且少于5次点击/按下,则应调用OneTimeClickAction
func ,
如果用户同时或连续5次且少于10次单击/按下,则应该调用FiveTimeClickAction
func
并且如果用户同时或连续单击10次以上单击/按下,则应该呼叫tenTimeClickAction
功能。
{
guard let tempDate = self.lastTappedAt else { return }
let elapsed = Date().timeIntervalSince(tempDate)
let duration = Int(elapsed)
print(duration)
if duration < 2 {
tapCount = tapCount + 1
// return
} else {
tapCount = 0
}
self.lastTappedAt = Date()
if tapCount > 9 {
let dispatchTime = DispatchTime.now() + 3.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.didTappedTenTimes(.happy)
}
return
}
if ((tapCount < 6) && (duration > 2)) {
let dispatchTime = DispatchTime.now() + 3.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.didTappedFiveTimes(.react)
}
return
}
if tapCount == 0{
let dispatchTime = DispatchTime.now() + 3.0
DispatchQueue.main.asyncAfter(deadline: dispatchTime) {
self.didTapped(.wink)
}
}
}
请随时让我进一步了解相同的内容,并建议我以更好的方式进行处理。
谢谢
答案 0 :(得分:1)
好吧,我知道您不想跟踪按下按钮时的实际时间,而只是在合理的时间内计算点击次数,假设多次点击属于同一动作(眨眼,开心,反应)。
var tapCount = 0
var lastTappedAt: Date = Date()
func scheduleCheckResult() {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
let timePassedSinceLastTap = Int(Date().timeIntervalSince(self.lastTappedAt))
print("last tap was \(timePassedSinceLastTap) ago")
// Wait a bit more for resolving final reaction. Adjust if you want quicker/slower taps (more than 1s for slower, less for quiceker)
guard timePassedSinceLastTap > 1 else {
return self.scheduleCheckResult()
}
print("FINISHED WITH: \(self.tapCount)")
// Verify result
switch self.tapCount {
case let n where n >= 10:
print("Super duper happy")
case let n where n >= 5:
print("Very happy")
default:
print("Medium happy")
}
// Reset state
self.tapCount = 0
}
}
@IBAction func didTap() {
if tapCount == 0 {
scheduleCheckResult()
}
lastTappedAt = Date()
tapCount += 1
}