Why does my UITableView not respond to touchesBegan?

后端 未结 3 917
-上瘾入骨i
-上瘾入骨i 2021-01-21 18:22

I am using this method

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

    UITouch *touch = [[event allTou         


        
相关标签:
3条回答
  • 2021-01-21 18:54

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

    0 讨论(0)
  • 2021-01-21 18:56

    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 讨论(0)
  • 2021-01-21 18:58

    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.

    0 讨论(0)
提交回复
热议问题