Perry Hoekstra
Perry Hoekstra

Reputation: 2763

In Swift, Detect Tap in Portion of UITableViewCell

Hopefully, this is an easy question for iOS/Swift developers. I have a UITableViewCell with text on the left and an image on the right. If the user taps on the row, I do something and that is working just fine. However, if the user taps on the image, I need to do something else. I took a look at Detect Tap on UIImageView within UITableViewCell but I don't translate Objective-C to Swift very well.

My assumption is that I need to do something like this in my subclassed UITableViewCell:

@IBOutlet var handsfreeImage: UIImageView!

override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
    super.init(style: style, reuseIdentifier: reuseIdentifier)

    let handsfreeTap = UITapGestureRecognizer(target: handsfreeImage, action:Selector("handsfreeTap:"))
}

func handsfreeTap(recognizer: UITapGestureRecognizer) {
    println("The handsfree image was tapped")
}

However, this is not working. Thoughts on what I am doing wrong?

Upvotes: 1

Views: 5060

Answers (3)

Perry Hoekstra
Perry Hoekstra

Reputation: 2763

So, I never was able to get the UITapGestureRecognizer approach to work (which is sad because I thought it was an elegant solution). So, I ended up using the delegate approach:

protocol HandsFreeTapCellDelegate {
    func handsFreeTap(handsFreeButton: VehicleTableViewCell)
}

class VehicleTableViewCell: UITableViewCell {

    var delegate : HandsFreeTapCellDelegate?

    @IBAction func handsFreeTap(sender: UIButton) {
        delegate?.handsFreeTap(self)
    }
}

class FooViewController: UIViewController, HandsFreeTapCellDelegate, UITableViewDelegate, UITableViewDataSource {
    func handsFreeTap(handsFreeButton: VehicleTableViewCell) {
        println("handsfreeButton was tapped, the row is: \(handsFreeButton.tag)")
    }
}

Upvotes: 2

Dima
Dima

Reputation: 23634

You are not using the UITapGestureRecognizer correctly.

The target should be the class that implements the handler method.

So it should be

let handsfreeTap = UITapGestureRecognizer(target: self, action:Selector("handsfreeTap:"))

Then you need to actually add the gesture recognizer to the view.

handsfreeImage.addGestureRecognizer(handsfreeTap)

That should all work. It might not still behave exactly the way you want because it will be missing some functionality such as long holds, and tap highlights. If these are things you care about, I would recommend simply using a UIButton with an image background instead of using a UIImageView because it handles all of that internally without you having to deal with it.

Upvotes: 4

Jeremy Pope
Jeremy Pope

Reputation: 3352

You created the recognizer, but you still need to add it to the view. So

whateverYourImageViewIs.addGestureRecognizer(handsfreeTap)

Upvotes: 2

Related Questions