0

So when ever I long press on a button, it recognizes the long press, but "test" gets called twice. How do I prevent that from happening?

@IBOutlet weak var button2: UIButton!

func longPressMe(){
   print("test")
}

func longPressGes(){
    let longpress = UILongPressGestureRecognizer(target: self, action: "longPressMe")
    longpress.minimumPressDuration = 1
    button2.addGestureRecognizer(longpress)
}


override func viewDidLoad() {
    super.viewDidLoad()
    longPressGes()
}

2 Answers2

3

You have to check the state of the gesture recognizer. Change longPressMe() to something like this:

func longPressMe(recognizer: UILongPressGestureRecognizer) {
    guard recognizer.state == .Began else { return }

    // do stuff here
}
Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
  • with bot my way and your way i keep getting *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[testtest.ViewController pressAction]: unrecognized selector sent to instance – DAMON GONZALEZ Apr 23 '16 at 10:54
  • You can't use a string for a selector anymore. Use the new `#selector` syntax instead. – Tim Vermeulen Apr 23 '16 at 11:12
  • @DAMONGONZALEZ change selector to `#selector(longPressMe(_:))` or if it is an old version of Xcode/Swift use `action: "longPressMe:"` – Leo Dabus Apr 23 '16 at 14:48
-1

Have a try, here is how to use #selector:

func longPressMe(recognizer: UILongPressGestureRecognizer) {
   // do stuff here
}

func longPressGes(){
    let longpress = UILongPressGestureRecognizer(target: self, action: #selector(yourViewController.longPressMe(_:)))
    longpress.minimumPressDuration = 1
    button2.addGestureRecognizer(longpress)
}
ilovecomputer
  • 4,238
  • 1
  • 20
  • 33