How to work with UILongPressGestureRecognizer in Swift using tables?

1

I need when the user presses the table cell to appear an alert with information.

Follow the code

import UIKit

class MyTableViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.title = "Bem da Água"
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let linha = indexPath.row
        println("Selecionou \(linha)")

        let Gest = UILongPressGestureRecognizer(target: self, action: "showAlerta:")
        self.view.addGestureRecognizer(Gest)
    }

    func showAlerta(sender: UILongPressGestureRecognizer){
        if sender.state == UIGestureRecognizerState.Began {
            var alerta = UIAlertController(title: "", message: "", preferredStyle: UIAlertControllerStyle.Alert)

            let show = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler:nil)

            alerta.addAction(show)

            presentViewController(alerta,animated:true,completion:nil)
        }
    }
}
    
asked by anonymous 15.07.2015 / 20:38

1 answer

1

You need to add the gesture in the cell itself, inside cellForRowAtIndexPath , for example:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier") as! UITableViewCell

    let gesture = UILongPressGestureRecognizer(target: self, action: "showAlerta:")
    cell.addGestureRecognizer(gesture)

    return cell
}

And to get the index path of the pressed cell, in your method showAlerta do:

func showAlerta(sender: UILongPressGestureRecognizer) {
    var point: CGPoint = sender.locationInView(tableView)
    var indexPath: NSIndexPath = tableView.indexPathForRowAtPoint(point)!
    // ...
}
    
15.07.2015 / 20:55