Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILongPressGestureRecognizer does not do anything

I wanted to have a UI button respond only if it is being held for more than a set number of seconds. So I used UILongPressGestureRecognizer as so:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var holdButton: UIButton!

@IBAction func holdButtonPressed(_ sender: Any) {
    let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPressHappened))
    recognizer.minimumPressDuration = 2.0
    view.addGestureRecognizer(recognizer)
}

and the handler

@objc func longPressHappened(gestureReconizer: UILongPressGestureRecognizer){
    holdButton.backgroundColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1)
    DispatchQueue.main.async {
         print ("Sucess")
    }
   
}

As you can see, i have used DispatchQueue and tried to change the color of the button but neither are working. Can someone please tell me why?

Update :- I am confused with implementing the methods given in the answer so i thought i will give my full code again

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var holdButton: UIButton! {
didSet {
    
         let recognizer = UILongPressGestureRecognizer(target: self,action: #selector(longPressHappened))
         recognizer.minimumPressDuration = 2.0
         holdButton.addGestureRecognizer(recognizer)
     }
 }

override func viewDidLoad() {
    super.viewDidLoad()
    
    holdButton.layer.cornerRadius = 150
    holdButton.layer.borderWidth = 1.0
    holdButton.layer.borderColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
    holdButton.clipsToBounds = true
}


@objc func longPressHappened(gestureReconizer: UILongPressGestureRecognizer){
    holdButton.backgroundColor = #colorLiteral(red: 0.7254902124, green: 0.4784313738, blue: 0.09803921729, alpha: 1)
    DispatchQueue.main.async {
         print ("Sucess")
    }
   
}

}
like image 234
Kingteena Avatar asked Oct 24 '25 02:10

Kingteena


1 Answers

You just need to create custom button using UIView. Add a long press gesture to that view and upon required time triggered the delegate/Closures.

func addLongPressGesture() {
    let recognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
    recognizer.minimumPressDuration = 3.0 // Duration
    customButton.addGestureRecognizer(recognizer)
}

@objc
func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state == .began {
        // Perform your functionality here
    }
}
like image 70
Jarvis The Avenger Avatar answered Oct 26 '25 04:10

Jarvis The Avenger