Victor Ippolitov Victor Ippolitov - 5 months ago 27
iOS Question

How to detect tap on clear part of UITableView?

I have view controller with UITableView. Height of table view is static and == height of screen. Number of rows in table can change and sometimes it might be a situation when number of rows is less than number of rows which can be visible, so appears some clear area on bottom of table. Can i detect tap on it without gesture recognizer? Are there some delegate methods of UITableView?


Yes, there are delegate methods, such as:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

However, this will only tell you if a tap occurs on an existing row. If you want to capture taps on the empty space below the rows (or on a section header) you will need to use a gesture recognizer. You can do something like this:

// in viewDidLoad or somewhere similar
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableTapped:)];
[self.tableView addGestureRecognizer:tap];

- (void)tableTapped:(UITapGestureRecognizer *)tap
    CGPoint location = [tap locationInView:self.tableView];
    NSIndexPath *path = [self.tableView indexPathForRowAtPoint:location];

        // tap was on existing row, so pass it to the delegate method
        [self tableView:self.tableView didSelectRowAtIndexPath:path];
        // handle tap on empty space below existing rows however you want