How to work with Uilongpressgesturerecognizer on Swift using tables?

Asked

Viewed 53 times

1

I need that when the user presses the table cell an alert with information appears.

Follows 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)
        }
    }
}

1 answer

1


It is necessary to add the gesture in the cell itself, inside the 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 its method showAlerta do:

func showAlerta(sender: UILongPressGestureRecognizer) {
    var point: CGPoint = sender.locationInView(tableView)
    var indexPath: NSIndexPath = tableView.indexPathForRowAtPoint(point)!
    // ...
}
  • Here returns me a bug guy in Identifier Cell

  • I don’t know what your method is like, which is how you assemble your cell, so I made an assumption to define the variable cell.

  • Exactly as you put it

  • Can you specify the error better? I could not identify where exactly is the error you quoted.

  • Ignore that mistake, because it was an oversight that I had and was resolved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.