I have a simple app which does some probability calculations. I have a plus button which increments a label value 0.1% at a time. What I want to do is increment it faster if I hold down the plus button. All the code I've searched for is for older versions of Swift or Xcode and I can't get my head around how to do it!
At the moment, I have returned to a functioning app with an @IBAction
func called plusButton
which just adds 0.1% to a label @IBOutlet
called preAssessmentProbability
.
I would be most grateful if anyone could help with telling me how to keep this functionality but add the ability to hold down the plusButton
to increment the preAssessmentProbability
label more rapidly (bonus gratitude if you can help with telling me how to set the rate of this).
Here is the implementation. First, make sure that you connect the three actions of your button in this way.
Then your code should look like
@IBAction func buttonUpInside(_ sender: Any) {
self.buttonUp()
}
@IBAction func buttonUpOutside(_ sender: Any) {
self.buttonUp()
}
@IBAction func buttonTouchDown(_ sender: Any) {
self.buttonDown()
}
func buttonDown() {
increaseSpeed()
holdTimer = Timer.scheduledTimer(timeInterval: 2, target: self, selector:#selector(increaseSpeed), userInfo: nil, repeats: true)
}
func buttonUp() {
speed = 1.0
holdTimer.invalidate()
addPercentTimer.invalidate()
}
func increaseSpeed(){
if speed != 1 {
addPercentTimer.invalidate()
}
if speed > 0 {
speed -= 0.2 //make it faster!
}
addPercentTimer = Timer.scheduledTimer(timeInterval: speed, target: self, selector:#selector(addPercent), userInfo: nil, repeats: true)
}
func addPercent(){
preAssessmentProbability += 0.1
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.