How can I detect taps to a specific area/rect of a UITableViewCell?

133 Views Asked by At

I have a UITableViewController that is using 4 custom UITableViewCell's.

2 of these custom cell's need a special behaviour.

Rather the detecting if a user selected a row/cell via didSelectRowAtIndexPath... I need to detect a tap more specifically.

For example, one of my custom cells is basically 2 buttons. A button on the left of the cell, and a button on the right.

1) Is the best way to do this, to just hook up the button's delegates to my viewcontroller, so the buttons work, or do I want to try and detect a specific rect/area that user tapped in?

4

There are 4 best solutions below

2
On

Just use target-action to observe the buttons. If you are having trouble with the cell eating touch events it should not, try overriding -hitTest:withEvent:.

0
On

You could user a UILabel instead if you don't feel confortable with UIButton. For example, You could add 2 UILabels on each side of the Custom UITableViewCell, resize them to fill the area you would like, then add 2 UITapGesturesRecognizers. I leave you here the steps:

  • Add 2 UILabels to the custom cell using the interface builder
  • Go to the Attributes Inspector tab, and find "User interaction enable" and enable it. (Do this for each UILabel)
  • Connect the UILabels to the Custom cell Controller (IBOutlet)
  • Add one UITapGesturesRecongnizer to each UiLabel
  • Create a Delegate to pass the Touch event from Custom cell class to TableView Controller to handle the Touch.

and thats it!

i'll leave here you a picture of how the Custom Cell could be

https://www.dropbox.com/s/u97n9yqtgd8x196/label.jpg?dl=0

let me know if you need something else!

Good luck.

0
On

Hook up the buttons, that's what they're for

0
On

Add this in your tableview's cellForRowAtIndexPath:

cell.selectionStyle = UITableViewCellSelectionStyleNone;

UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(methodToCallWhenPressed)];
[tap setNumberOfTouchesRequired:1];
[tap setNumberOfTapsRequired:1];
[cell.button addGestureRecognizer:tap];

You will also need to create an IBOutlet from the button in the custom cell.