开发者

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 isFirstRe开发者_如何学编程sponder] && [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?


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.


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];


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];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜