How to handle a tapping on non-cell area of UITableView

ios, objective-c, uitableview, uitapgesturerecognizer

Solution

Try this: initialize and add the UITapGestureRecognizer to your tableView:

UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc]  initWithTarget:self action:@selector(tap:)];
gr.delaysTouchesBegan = YES;
gr.delegate = self;
[_tableView addGestureRecognizer:gr];

implement the gesture recognizer delegate method:

-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    CGPoint tapPoint = [gestureRecognizer locationInView:_tableView];
    UIView * clickedView = [_tableView hitTest:tapPoint withEvent:nil];
    NSString *viewClassName = NSStringFromClass(clickedView.class);
    return ![viewClassName hasPrefix:@"UITableViewCell"];
}

this way every tap you do outsude cells (but inside the tableview) will be recognized with your `UITapGestureRecognizer`

Problem

I have a `UITableView` with a couple of `UITableViewCells` in it. Because I only have a couple of cells, there is an area of the table view that's not covered by the cells. And I want to do something when the empty area is tapped. I tried adding a `UITapGestureRecognizer` on the table view. It detects the tapping on the empty area, but then the cells fail to respond to tapping. I tried adding the tap gesture recognizer on the super view of the table view, but the result is the same. There must be a way to do this, but I can't quite figure it out yet. Is there any way to achieve what I want to do?

Original source

Related problems