Ios – Adding a Tap Gesture Recognizer to TableViewCell.swift

iosswiftuitableview

I have a table view cell with an image that I have attached a Tap Gesture Recognizer to.

Image of prototype TableViewCell in Table View with two labels and an image. At the top there is the Tap Gesture Recognizer logo:

enter image description here

When I attempt to ctrl and drag the Tap Gesture Recognizer to the TableViewCellController, TableViewCell files or any other file, it won't let me.

However, on my other view that isn't a table view, I can get this to work fine. I'm new to Swift. Would anyone know why this is happening, and what I can do to help it (I know I could use a button instead, but I wouldn't learn anything from that)?

Both the TableViewCell and TableViewCellController files have their default code.

Edit: What I want is for the user to be able to tap the image to add +1 to a Int property in the class in the table cell. One of the UILabels in the class, and the cell, is updated. This is the kind of behaviour I can achieve without problem in a regular view and want to achieve in the table view.

Best Answer

For UITableViewCell you cannot add a UITapgesture to it via storyboard because it is just a prototype cell unlike others. If you really want to do that you can do it programatically in the delegate like this:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    let tapGesture = UITapGestureRecognizer(target: self, action: "SomeMethod")
    cell.myImageView.addGestureRecognizer(tapGesture)

    return cell
}

But i can't find out why you want to do that. If you just want to do something or call some function when cell is tapped, you should be using the didSelectRowAtIndexPath.

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    print("cell at #\(indexPath.row) is selected!")
}