Press-and-hold button for "repeat fire" - ios

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.

You want rapid repeat fire when your button is held down.
Your buttonDown and buttonUp 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 #IBActions from the Storyboard and just set up the button in viewDidLoad:
class ViewController: UIViewController {
#IBOutlet weak var button: UIButton!
var timer: Timer?
var speedAmmo = 20
#objc func buttonDown(_ sender: UIButton) {
singleFire()
timer = Timer.scheduledTimer(timeInterval: 0.3, target: self, selector: #selector(rapidFire), userInfo: nil, repeats: true)
}
#objc func buttonUp(_ sender: UIButton) {
timer?.invalidate()
}
func singleFire() {
print("bang!")
}
#objc func rapidFire() {
if speedAmmo > 0 {
speedAmmo -= 1
print("bang!")
} else {
print("out of speed ammo, dude!")
timer?.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// These could be added in the Storyboard instead if you mark
// buttonDown and buttonUp with #IBAction
button.addTarget(self, action: #selector(buttonDown), for: .touchDown)
button.addTarget(self, action: #selector(buttonUp), for: [.touchUpInside, .touchUpOutside])
}
}
Also, I changed .touchUpOutside to [.touchUpInside, .touchUpOutside] (to catch both touch up events) and call singleFire on the initial buttonDown for single fire. With these changes, pressing the button fires immediately, and then fires every 0.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 to buttonDown and buttonUp. Then Control-click on your button in the Storyboard and drag from the circle next to Touch Down to func buttonDown, and drag from the circles next to Touch Up Inside and Touch Up Outside to func buttonUp.

In my original answer, I answered the question of how to have a button recognize both a tap and a long press. In the clarified question, it appears you want this button to continuously "fire" as long as the user holds their finger down. If that's the case, only one gesture recognizer is needed.
For example, in Interface Builder, drag a long press gesture recognizer from the object library onto the button and then set the "Min Duration" to zero:
Then you can control-drag from the long press gesture recognizer to your code in the assistant editor and add an #IBAction to handle the long press:
weak var timer: Timer?
#IBAction func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { [weak self] timer in
guard let self = self else {
timer.invalidate()
return
}
self.handleTimer(timer)
}
} else if gesture.state == .ended || gesture.state == .cancelled {
timer?.invalidate()
}
}
func handleTimer(_ timer: Timer) {
print("bang")
}
Or, if you also want to stop firing when the user drags their finger off of the button, add a check for the location of the gesture:
#IBAction func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == .began {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true) { [weak self] timer in
guard let self = self else {
timer.invalidate()
return
}
self.handleTimer(timer)
}
} else if gesture.state == .ended || gesture.state == .cancelled || (gesture.state == .changed && !gesture.view!.bounds.contains(gesture.location(in: gesture.view))) {
timer?.invalidate()
}
}
My original answer, answering the different question of how to recognize both taps and long presses on a button, is below:
Personally, I'd use tap and long press gesture recognizers, e.g.:
override func viewDidLoad() {
super.viewDidLoad()
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
button.addGestureRecognizer(longPress)
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
tap.shouldRequireFailure(of: longPress)
button.addGestureRecognizer(tap)
}
#objc func handleTap(_ gesture: UITapGestureRecognizer) {
print("tap")
}
#objc func handleLongPress(_ gesture: UILongPressGestureRecognizer) {
if gesture.state == .Began {
print("long press")
}
}
If you want, with the long press gesture, you could perform your action upon .Ended, too. It just depends upon the desired UX.
FYI, you can also add these two gesture recognizers right in Interface Builder, too, (just drag the respective gestures from the object library on to the button and then control-drag from the gesture recognizer to #IBAction functions) but it was easier to illustrate what's going on by showing it programmatically.

I took a different approach when coming up with my own solution. I created a UIButton subclass and enclosed all the solution inside. The difference is that instead of using an IBAction for the handler I created a property in the UIButton
class RapidFireButton: UIButton {
private var rapidFireTimer: Timer?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
init() {
super.init(frame: .zero)
commonInit()
}
private func commonInit() {
addTarget(self, action: #selector(touchDownHandler), for: .touchDown)
addTarget(self, action: #selector(touchUpHandler), for: .touchUpOutside)
addTarget(self, action: #selector(touchUpHandler), for: .touchUpInside)
}
#objc private func touchDownHandler() {
rapidFireTimer?.invalidate()
rapidFireTimer = nil
tapHandler(self)
rapidFireTimer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true, block: { [unowned self] (timer) in
self.tapHandler(self)
})
}
#objc private func touchUpHandler() {
rapidFireTimer?.invalidate()
rapidFireTimer = nil
}
var tapHandler: (RapidFireButton) -> Void = { button in
}
}
Usage is basically creating an outlet for the button and implementing the handler like so
rapidFireButton.tapHandler = { button in
//do stuff
}

I updated #vacawama example codes to swift 3. Thanks.
#IBOutlet var button: UIButton!
var timer: Timer!
var speedAmmo = 100
#IBAction func buttonDown(sender: AnyObject) {
singleFire()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(rapidFire), userInfo: nil, repeats: true)
}
#IBAction func buttonUp(sender: AnyObject) {
timer.invalidate()
}
func singleFire() {
if speedAmmo > 0 {
speedAmmo -= 1
print("bang!")
} else {
print("out of speed ammo, dude!")
timer.invalidate()
}
}
func rapidFire() {
if speedAmmo > 0 {
speedAmmo -= 1
print("bang!")
} else {
print("out of speed ammo, dude!")
timer.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action:#selector(buttonDown(sender:)), for: .touchDown)
button.addTarget(self, action:#selector(buttonUp(sender:)), for: [.touchUpInside, .touchUpOutside])
}

Swift 5+
Based on rob's answer there is a nicer way to do this now.
Add the long press gesture recognizer by dragging it on-top of the button in the storyboard and then ...
Then you can control-drag from the long press gesture recognizer to
your code in the assistant editor and add an #IBAction to handle the
long press:
- Quote from Rob's Answer
The difference is in the code which is listed below:
var timer: Timer?
#IBAction func downButtonLongPressHandler(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
timer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true, block: {_ in
self.downButtonPressedLogic()
self.doCalculations()
})
} else if sender.state == .ended || sender.state == .cancelled {
print("FINISHED UP LONG PRESS")
timer?.invalidate()
timer = nil
}
}
You no longer need to use NSTimer, you can just use Timer now and you can just put the code for the timer in the block which is much more compact and no need for selectors.
In my case I had another function that handles the logic for what to do when the downButton was pressed, but you can put your code you want to handle in there.
You can control the speed of the repeat fire by changing the withTimeInterval parameter value.
You can change the timing for the timer to start by finding the longPressGesture in your storyboard and changing it's Min Duration value. I usually set mine at 0.5 so that your normal button press actions can still work (unless you don't care about that). If you set it to 0 this will ALWAYS override your normal button press actions.

You can use Timer
follow this example on github
https://github.com/sadeghgoo/RunCodeWhenUIbuttonIsHeld

viewDidLoad
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.touchHoldView(sender:)))
longPressGesture.minimumPressDuration = 2
myUIView.addGestureRecognizer(longPressGesture)
#objc func touchHoldView(sender: UITapGestureRecognizer) {
if sender.state == .began {
//code..
}
}

Related

fade in button so it won't automatically fade out again

I'm using a tap gesture recogniser so if the user taps on the screen the button fades out for 5 seconds and then if the user wants to see the buttons on the screen again they tap on the screen and the button fades in.
The Problem is:
I can't disable the button when it fades in so it won't automatically fade out again. I tried to invalidate the timer but that didn't work. To be more specific of what I want to do:
On app load, you see an enabled "Start Stop Button." - Tap anywhere on the screen and a 5 second timer starts to fade the button out and disables it. Once the button fades out and disables, I can tap anywhere on the screen to fade the button back in, enable it, and kill the timer so the button shows up as it was before I first tapped it.
class ViewController: UIViewController {
// Create these 3 properties in the top of your class
var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
var timer = Timer() // Create the timer!
var isTimerRunning: Bool = false // Need this to prevent multiple timers from running at the same time.
#IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.
override func viewDidLoad() {
super.viewDidLoad()
startStopButton.isEnabled = true
runTimer()
// Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
self.view.addGestureRecognizer(tapRecognizer)
}
func runTimer() {
// Create the timer to run a method (in this case... updateTimer) every 1 second.
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
// Set the isTimerRunning bool to true
isTimerRunning = true
}
#objc func updateTimer() {
// Every 1 second that this method runs, 1 second will be chopped off the secondToFadeOut property. If that hits 0 (< 1), then run the fadeOutButton and invalidate the timer so it stops running.
secondToFadeOut -= 1
print(secondToFadeOut)
if secondToFadeOut < 1 {
fadeOutButton()
timer.invalidate()
isTimerRunning = false
}
}
#objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
// When the view is tapped (based on the gesture recognizer), reset the secondToFadeOut property, fade in (and enable) the button.
//secondToFadeOut = 5
fadeInButton()
timer.invalidate()
//if isTimerRunning == false {
// runTimer()
//}
}
func fadeOutButton() {
// Fade out your button! I also disabled it here. But you can do whatever your little heart desires.
UIView.animate(withDuration: 0.5) {
self.startStopButton.alpha = 0.25
}
self.startStopButton.isEnabled = false
}
func fadeInButton() {
// Fade the button back in, and set it back to active (so it's tappable)
UIView.animate(withDuration: 0.5) {
self.startStopButton.alpha = 1
}
self.startStopButton.isEnabled = true
}
#IBAction func startStopButtonPressed(_ sender: UIButton) {
print("Start Stop Button Pressed")
}
}
My best guess is that you have a rogue Timer object that remains in memory even after you invalidate your current timer, and that is causing the button to fade out again after it fades in.
I have made several edits to your class. Check the code out:
class ViewController: UIViewController {
// Create these 3 properties in the top of your class
var secondToFadeOut = 5 // How many second do you want the view to idle before the button fades. You can change this to whatever you'd like.
var timer? = nil // Create the timer!
#IBOutlet weak var startStopButton: UIButton! // The outlet for your button. This is used to fade it in and out, and enable / disable it.
override func viewDidLoad() {
super.viewDidLoad()
startStopButton.isEnabled = true
runTimer()
// Add a tap gesture recognizer to the main view to determine when the screen was tapped (for the purpose of resetting the timer).
let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.tap(_:)))
self.view.addGestureRecognizer(tapRecognizer)
}
func runTimer() {
if timer == nil {
timer = Timer.scheduledTimer(timeInterval: secondToFadeOut, target: self, selector: (#selector(ViewController.timerFired)), userInfo: nil, repeats: false)
}
}
#objc func timerFired() {
timer = nil
if self.startStopButton.isEnabled {
fadeOutButton()
} else {
fadeInButton()
}
}
#objc func tap(_ gestureRecognizer: UITapGestureRecognizer) {
runTimer()
}
func fadeOutButton() {
UIView.animate(withDuration: 0.5) {
self.startStopButton.alpha = 0.25
}
self.startStopButton.isEnabled = false
}
func fadeInButton() {
UIView.animate(withDuration: 0.5) {
self.startStopButton.alpha = 1
}
self.startStopButton.isEnabled = true
}
#IBAction func startStopButtonPressed(_ sender: UIButton) {
print("Start Stop Button Pressed")
}
}

How to make a timer that starts with a long press on the button?

I'm currently learning Swift and iOS programming. I want to make a timer that starts with a long press on the button. At the same time I want to change the UIButton image. I leave button, I want the button revert back. Is this possible?
You absolutely can do this. You have to add LongPressGestureRecognizer:
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(yourAction))
button.addGestureRecognizer(longPress)
And then in your func start the timer and change the button's image:
func yourAction(){
Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(timerAction), userInfo: nil, repeats: false)
button.setImage(UIImage(named: "yourImage"), for: .normal)
}
func timerAction(){
//Do whatever you want
}
You need to implement your own solution for this, something along the lines
1- User touches down (UIControlEvent touchDown), you start a time that fires every x secs/millisecs
2- Timer will fire the action over and over
3- User touches up UICOntrolEvent touchUp, you cancel your timer
So you bind those 2 events to different functions, and start/kill your timers with appropriate actions
How that helps
I will add a code for demonstration:
#IBOutlet var button: UIButton!
var timer: Timer!
var speedAmmo = 100
#IBAction func buttonDown(sender: AnyObject) {
singleFire()
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(rapidFire), userInfo: nil, repeats: true)
}
#IBAction func buttonUp(sender: AnyObject) {
timer.invalidate()
}
func singleFire() {
if speedAmmo > 0 {
speedAmmo -= 1
print("bang!")
} else {
print("out of speed ammo, dude!")
timer.invalidate()
}
}
func rapidFire() {
if speedAmmo > 0 {
speedAmmo -= 1
print("bang!")
} else {
print("out of speed ammo, dude!")
timer.invalidate()
}
}
override func viewDidLoad() {
super.viewDidLoad()
button.addTarget(self, action:#selector(buttonDown(sender:)), for: .touchDown)
button.addTarget(self, action:#selector(buttonUp(sender:)), for: [.touchUpInside, .touchUpOutside])
}
Please try and let me know!

Button tap and long press gesture

I'm having a little trouble with the gestures.
I'm trying to use both tap and long press on the same button, so I've used
#IBAction func xxx (sender: UITapGestureRecognizer)
and
#IBAction func xxx (sender: UILongPressGestureRecognizer)
but my button seems to react to both functions when I tap. What might be wrong?
func long(longpress: UIGestureRecognizer){
if(longpress.state == UIGestureRecognizerState.Ended){
homeScoreBool = !homeScoreBool
}else if(longpress.state == UIGestureRecognizerState.Began){
print("began")
}
}
Hard to say what´s not working with your code, with the only two rows that you have provided, but I would recommend you to do it in this way instead:
Create an outlet to your button instead
#IBOutlet weak var myBtn: UIButton!
And in your viewDidLoad() add the gestures to the buttons
let tapGesture = UITapGestureRecognizer(target: self, action: "normalTap")
let longGesture = UILongPressGestureRecognizer(target: self, action: "longTap:")
tapGesture.numberOfTapsRequired = 1
myBtn.addGestureRecognizer(tapGesture)
myBtn.addGestureRecognizer(longGesture)
And then create the actions to handle the taps
func normalTap(){
print("Normal tap")
}
func longTap(sender : UIGestureRecognizer){
print("Long tap")
if sender.state == .Ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
}
else if sender.state == .Began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
}
}
Swift 3.0 version:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.normalTap))
let longGesture = UILongPressGestureRecognizer(target: self, action: Selector(("longTap:")))
tapGesture.numberOfTapsRequired = 1
myBtn.addGestureRecognizer(tapGesture)
myBtn.addGestureRecognizer(longGesture)
func normalTap(){
print("Normal tap")
}
func longTap(sender : UIGestureRecognizer){
print("Long tap")
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
}
else if sender.state == .began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
}
}
Updated syntax for Swift 5.x:
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(normalTap))
button.addGestureRecognizer(tapGesture)
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(longTap))
button.addGestureRecognizer(longGesture)
#objc func normalTap(_ sender: UIGestureRecognizer){
print("Normal tap")
}
#objc func longTap(_ sender: UIGestureRecognizer){
print("Long tap")
if sender.state == .ended {
print("UIGestureRecognizerStateEnded")
//Do Whatever You want on End of Gesture
}
else if sender.state == .began {
print("UIGestureRecognizerStateBegan.")
//Do Whatever You want on Began of Gesture
}
}

UIButton with single press and long press events swift

I want to trigger two action on button click and button long click. I have add a UIbutton in my interface builder. How can i trigger two action using IBAction can somebody tell me how to archive this ?
this is the code i have used for a button click
#IBAction func buttonPressed (sender: UIButton) {
....
}
can i use this method or do i have to use another method for long click ?
If you want to perform any action with single tap you and long press the you can add gestures into button this way:
#IBOutlet weak var btn: UIButton!
override func viewDidLoad() {
let tapGesture = UITapGestureRecognizer(target: self, #selector (tap)) //Tap function will call when user tap on button
let longGesture = UILongPressGestureRecognizer(target: self, #selector(long)) //Long function will call when user long press on button.
tapGesture.numberOfTapsRequired = 1
btn.addGestureRecognizer(tapGesture)
btn.addGestureRecognizer(longGesture)
}
#objc func tap() {
print("Tap happend")
}
#objc func long() {
print("Long press")
}
This way you can add multiple method for single button and you just need Outlet for that button for that..
#IBOutlet weak var countButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
addLongPressGesture()
}
#IBAction func countAction(_ sender: UIButton) {
print("Single Tap")
}
#objc func longPress(gesture: UILongPressGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.began {
print("Long Press")
}
}
func addLongPressGesture(){
let longPress = UILongPressGestureRecognizer(target: self, action: #selector(longPress(gesture:)))
longPress.minimumPressDuration = 1.5
self.countButton.addGestureRecognizer(longPress)
}
Why not create a custom UIButton class, create a protocol and let the button send back the info to delegte. Something like this:
//create your button using a factory (it'll be easier of course)
//For example you could have a variable in the custom class to have a unique identifier, or just use the tag property)
func createButtonWithInfo(buttonInfo: [String: Any]) -> CustomUIButton {
let button = UIButton(type: .custom)
button.tapDelegate = self
/*
Add gesture recognizers to the button as well as any other info in the buttonInfo
*/
return button
}
func buttonDelegateReceivedTapGestureRecognizerFrom(button: CustomUIButton){
//Whatever you want to do
}

Swift: Long Press Gesture Recognizer - Detect taps and Long Press

I want to wire an action such that if the gesture is a tap, it does animates an object in a particular way but if the press duration was more than .5 secs it does something else.
Right now, I just have the animation hooked up. I don't know how I can differentiate between a long press and a tap?
How do I access the press duration to achieve the above?
#IBAction func tapOrHold(sender: AnyObject) {
UIView.animateKeyframesWithDuration(duration, delay: delay, options: options, animations: {
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0, animations: {
self.polyRotate.transform = CGAffineTransformMakeRotation(1/3 * CGFloat(M_PI * 2))
})
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0, animations: {
self.polyRotate.transform = CGAffineTransformMakeRotation(2/3 * CGFloat(M_PI * 2))
})
UIView.addKeyframeWithRelativeStartTime(0, relativeDuration: 0, animations: {
self.polyRotate.transform = CGAffineTransformMakeRotation(3/3 * CGFloat(M_PI * 2))
})
}, completion: { (Bool) in
let vc : AnyObject! = self.storyboard?.instantiateViewControllerWithIdentifier("NextView")
self.showViewController(vc as UIViewController, sender: vc)
})
Define two IBActions and set one Gesture Recognizer to each of them. This way you can perform two different actions for each gesture.
You can set each Gesture Recognizer to different IBActions in the interface builder.
#IBAction func tapped(sender: UITapGestureRecognizer)
{
println("tapped")
//Your animation code.
}
#IBAction func longPressed(sender: UILongPressGestureRecognizer)
{
println("longpressed")
//Different code
}
Through code without interface builder
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: "tapped:")
self.view.addGestureRecognizer(tapGestureRecognizer)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "longPressed:")
self.view.addGestureRecognizer(longPressRecognizer)
func tapped(sender: UITapGestureRecognizer)
{
println("tapped")
}
func longPressed(sender: UILongPressGestureRecognizer)
{
println("longpressed")
}
Swift 5
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(tapped))
self.view.addGestureRecognizer(tapGestureRecognizer)
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressed))
self.view.addGestureRecognizer(longPressRecognizer)
#objc func tapped(sender: UITapGestureRecognizer){
print("tapped")
}
#objc func longPressed(sender: UILongPressGestureRecognizer) {
print("longpressed")
}
For swift2
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
lpgr.minimumPressDuration = 0.5
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
self.featuredCouponColView.addGestureRecognizer(lpgr)
Action
//MARK: - UILongPressGestureRecognizer Action -
func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizerState.Ended {
//When lognpress is start or running
}
else {
//When lognpress is finish
}
}
For Swift 4.2/ Swift 5
let lpgr = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress))
lpgr.minimumPressDuration = 0.5
lpgr.delaysTouchesBegan = true
lpgr.delegate = self
self.colVw.addGestureRecognizer(lpgr)
//MARK: - UILongPressGestureRecognizer Action -
#objc func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
if gestureReconizer.state != UIGestureRecognizer.State.ended {
//When lognpress is start or running
}
else {
//When lognpress is finish
}
}
Through code without interface builder
// Global variables declaration
var longPressed = false
var selectedRow = 0
override func viewDidLoad() {
super.viewDidLoad()
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(ContactListTableViewController.handleLongPress(_:)))
longPressGesture.minimumPressDuration = 1.0 // 1 second press
longPressGesture.allowableMovement = 15 // 15 points
longPressGesture.delegate = self
self.tableView.addGestureRecognizer(longPressGesture)
}
// Long tap work goes here !!
if (longPressed == true) {
if(tableView.cellForRowAtIndexPath(indexPath)?.accessoryType == .Checkmark){
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .None
self.selectedRow -= 1
if(self.selectedRow == 0){
self.longPressed = false
}
} else {
self.selectedRow += 1
tableView.cellForRowAtIndexPath(indexPath)?.accessoryType = .Checkmark
}
} else if(self.selectedRow == 0) {
// Single tape work goes here !!
}
But the only problem is the long press gesture runs two times. If you have found any solution do comment below !
Swift 5 using interface builder
for the normal tap you can simply create a touch up inside action from your button.
for the long press, create an outlet for your button, create the tap gesture recognizer and set it to the button then create the selector method to perform the long press tasks.
#IBOutlet var myButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(addToListButtonLongPress(_:)))
longPressRecognizer.numberOfTouchesRequired = 1
longPressRecognizer.allowableMovement = 10
longPressRecognizer.minimumPressDuration = 0.5
myButton.addGestureRecognizer(longPressRecognizer)
}
// Connected to myButton in interface builder.
#IBAction func myButtonTapped(_ sender: UIButton) {
print("button tapped")
}
#objc func myButtonLongPressed(_ sender: UILongPressGestureRecognizer) {
print("button long pressed")
}

Resources