johnniexo88 johnniexo88 - 3 months ago 42
iOS Question

How to get cell on label or imageview tap - UITapGestureRecognizer

My goal is to perform segue when i tap on imageview of that cell. but the error does not appear when i use

addTarget
on a button.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
cell.imageView.userInteractionEnabled = true
let tapImageView = UITapGestureRecognizer(target: self, action: #selector(HomeFeedViewController.tapImageView(_:)))
cell.imageView.addGestureRecognizer(tapImageView)
return cell as CastleCell
}

func tapImageView(sender: AnyObject) {
let center = sender.center
let point = sender.superview!!.convertPoint(center, toView:self.tableView) //line of error
let indexPath = self.tableView.indexPathForRowAtPoint(point)
let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! CastleCell

performSegueWithIdentifier("SegueName", sender: self)
}


The line of error is
let point =
...

The error i get is:


fatal error: unexpectedly found nil while unwrapping an Optional value
(lldb)


but the error does not appear when i use
addTarget
on a button. what could be wrong? thanks.

Answer

Am not really fond of playing with points and Superview. What is can suggest is to make a class for UITapGestureRecognizer as follows which can hold extra data. In your case it would be an index path

class CustomGesture: UITapGestureRecognizer {
    let indexPath:NSIndexPath? = nil
}

And then in your didSelect you can add the index path to the newly created CustomGesture class which be would be like:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        cell.imageView.userInteractionEnabled = true
        let tapImageView = CustomGesture(target: self, action: #selector(HomeFeedViewController.tapImageView(_:)))
        tapImageView.indexPath = indexPath// Add the index path to the gesture itself
        cell.imageView.addGestureRecognizer(tapImageView)
        return cell as CastleCell
    }

Now since you have added the indexPath you don't need to play around with super view's and you can access the cell like this:

func tapImageView(gesture: CustomGesture) {

        let indexPath = gesture.indexPath!
        let cell = self.tableView.cellForRowAtIndexPath(indexPath!) as! CastleCell

        performSegueWithIdentifier("SegueName", sender: self)
    }
Comments