JohnCarp
JohnCarp

Reputation: 49

Why isn't my UILongPressGestureRecognizer working?

I have the following code and my long press is not working the way it should. Can anybody figure out why it isn't working?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "myButton:")
    longPressRecognizer.minimumPressDuration = 0.5
    myButton.addGestureRecognizer(longPressRecognizer)
}

@IBOutlet weak var myButton: UIButton!

@IBAction func myButton(longPress: UILongPressGestureRecognizer) {

    if longPress.state != .Began {

        presentAlertController()

        return
    }
}

This error comes up when i Hold down on the button

2016-01-09 00:41:28.785 longPressTest[1870:551106] Warning: Attempt to present <UIAlertController: 0x144d6a500>  on <longPressTest.ViewController: 0x144e3a450> which is already presenting <UIAlertController: 0x144e59d80>
2016-01-09 00:41:28.903 longPressTest[1870:551106] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x144d6a500>)
2016-01-09 00:41:28.905 longPressTest[1870:551106] Warning: Attempt to present <UIAlertController: 0x144e54bb0>  on <longPressTest.ViewController: 0x144e3a450> which is already presenting <UIAlertController: 0x144e59d80>
Cancel 

Upvotes: 0

Views: 816

Answers (1)

rob mayoff
rob mayoff

Reputation: 385970

A long press gesture is a continuous gesture. That means that the recognizer will call your function (myButton(_:)) when it detects the start of the long press (after 0.5 seconds) with state == .Began, and repeatedly as the touch moves on the screen with state == .Changed, and once more when the gesture ends with state == .Ended. You're trying to present the alert on every .Changed call and on the .Ended call, and you get errors when you try to present an alert that's already being presented.

If you want to present the alert as soon as 0.5 seconds have elapsed, do it when the state is .Began, not when the state is anything except .Began.

@IBAction func myButton(longPress: UILongPressGestureRecognizer) {
    if longPress.state == .Began {
        presentAlertController()
    }
}

You only get one call with state .Began, so you won't try to present the alert again while it's already being presented.

Upvotes: 6

Related Questions