I have strange issue – when I register TapGestureRecognizer in the cellForRowAtIndexPath method it works perfect, but when I register TapGestureRecognizer in cell’s initWithStyle method tap recognition doesn’t work, breakpoint doesn’t hit in handler.
The following works.
I have created custom table view cell with corresponding xib file and registered it.
[self.tableView registerNib:[UINib nibWithNibName:@"MyCell"
bundle:[NSBundle mainBundle]]
forCellReuseIdentifier:@"cell"];
...
and in the cellForRowAtIndexPath
MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
...
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self
action:@selector(didTapCell:)];
[tap setNumberOfTapsRequired:1];
[cell addGestureRecognizer:tap];
The following doesn’t work
@implementation MyCell
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
UITapGestureRecognizer *tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCellTap:)];
[tgr setDelegate:self];
[tgr setNumberOfTapsRequired:1];
[tgr setNumberOfTouchesRequired:1];
[self addGestureRecognizer:tgr];
//[self.contentView addGestureRecognizer:tgr]; also doesn't work
}
return self;
}
I can leave the working solution, but I want to move the gesture recognition to cell initialization and fire tap event through my delegate.
Why is tap recognition not working if I’m registering recognizer in the cell initialization?
You have registered a xib for a particular cell identifier. Now the tableview will automatically instantiate a cell for you if needed (when you call dequeReusableCell…) but the initWithStyle:reuseIdentifier method does not get called, so your gesture recognizer is never created/added.
If you do need to ‘init’ stuff when using registered xib(s), override the awakeFromNib in your custom cell class and put your code there. I usually put my ‘init’ code in a separate method and call it from both initWithStyle and awakeFromNib overrides.