Thomas N.
Thomas N.

Reputation: 21

Why does my UITableView not respond to touchesBegan?

I am using this method

- (void)tableView:(UITableView *)tableView touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    if ([myPickerView isFirstResponder] && [touch view] != myPickerView) {
        [myPickerView resignFirstResponder];
    }
    [super touchesBegan:touches withEvent:event];
}

but my tableView does not respond to touches (applied to the view works, but this is covered by the tableView!)

If this is not possible - is there any other possibility to capture "out of window" touches?

Upvotes: 2

Views: 9086

Answers (3)

Miguel Ehrstrand
Miguel Ehrstrand

Reputation: 71

Here is a UITableView subclass solution that worked for me. Make a subclass of UITableView and override hitTest:withEvent: as below:

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {

    static UIEvent *e = nil;

    if (e != nil && e == event) {
        e = nil;
        return [super hitTest:point withEvent:event];
    }

    e = event;

    if (event.type == UIEventTypeTouches) {
        NSSet *touches = [event touchesForView:self];
        UITouch *touch = [touches anyObject];
        if (touch.phase == UITouchPhaseBegan) {
            NSLog(@"Touches began");
        }
    }
    return [super hitTest:point withEvent:event];
}

Upvotes: 0

Steph Sharp
Steph Sharp

Reputation: 11672

I found the simplest way to do this is to add a gesture recognizer to the UITableViewController's view.

I put this code in the UITableViewController's viewDidLoad:

UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self.view addGestureRecognizer:tap];

And implemented the event handler:

- (void)handleTap:(UITapGestureRecognizer *)recognizer
{
    // your code goes here...
}

EDIT: You could also add the gesture recognizer to the tableview, just change [self.view addGestureRecognizer:tap]; to [self.tableView addGestureRecognizer:tap];

Upvotes: 11

Rob Napier
Rob Napier

Reputation: 299265

There is no such delegate method as tableView:touchesBegan:withEvent:. If you want to override -touchesBegan:withEvent: for your UITableView, you will need to subclass UITableView. Most problems like this are often better implemented with a UIGestureRecognizer. In the above, I'd probably use a UITapGestureRecognizer.

Upvotes: 12

Related Questions