I have referred to countless other questions about a press-and-hold button but there aren't many related to Swift. I have one function connected to a button using the touchUpInside event:
@IBAction func singleFire(sender: AnyObject){
//code
}
…and another function that is meant to call the function above repeatedly while the same button is held down, and stop when the button is no longer pressed:
@IBAction func speedFire(sender: AnyObject){
button.addTarget(self, action: "buttonDown:", forControlEvents: .TouchDown)
button.addTarget(self, action: "buttonUp:", forControlEvents: .TouchUpOutside)
func buttonDown(sender: AnyObject){
timer = NSTimer.scheduledTimerWithTimeInterval(0.3, target: self, selector: "singleFire", userInfo: nil, repeats: true)
}
func buttonUp(sender: AnyObject){
timer.invalidate()
}
}
I'm not sure what I'm doing wrong, and I don't know how to setup touch events to the same button for a different function.
Best Answer
You want rapid repeat fire when your button is held down.
Your
buttonDown
andbuttonUp
methods need to be defined at the top level, and not inside of another function. For demonstration purposes, it is clearer to forgo wiring up@IBAction
s from the Storyboard and just set up the button inviewDidLoad
:Also, I changed
.touchUpOutside
to[.touchUpInside, .touchUpOutside]
(to catch both touch up events) and callsingleFire
on the initialbuttonDown
for single fire. With these changes, pressing the button fires immediately, and then fires every0.3
seconds for as long as the button is held down.The button can be wired up in the Storyboard instead of setting it up in
viewDidLoad
. In this case, add@IBAction
tobuttonDown
andbuttonUp
. Then Control-click on your button in the Storyboard and drag from the circle next to Touch Down tofunc buttonDown
, and drag from the circles next to Touch Up Inside and Touch Up Outside tofunc buttonUp
.