I have made a bit of code that when the user taps everywhere on the screen the points/score/taps will increment by 1. But the problem is then it counts how many continuous taps I make and then if I leave a 1 second gap between pressing it will restart the counter. Is there any way I could make it stop restarting?
CODE:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var tapsLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as! UITouch
let tapCount = touch.tapCount
tapsLabel.text = "Taps: \(tapCount)"
}
}
The tapCount
documentation says:
The value of this property is an integer indicating the number of times the user tapped their fingers on a certain point within a predefined period.
It's supposed to reset after some “predefined period”. You're trying to use it for something it wasn't designed for.
Instead, you need to create a property on ViewController
to count the number of total taps:
class ViewController: UIViewController {
private var tapCount = 0
@IBOutlet weak var tapsLabel: UILabel!
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
tapCount += 1
tapsLabel.text = "Taps: \(tapCount)"
}
}
(Please note that my code here is for the iOS 9 API. The touchesBegan:withEvent:
method signature is slightly different than in the iOS 8 API.)