Keyboard dismiss and UITableView touch issue

2019-06-14 14:07发布

问题:

So I have this UITableView that contains few rows, when clicked on a row, another UIViewController is pushed with the specific row details. My problem is that I want to dismiss keyboard with any touch on the screen (also on the UITableView), but when I do it, and click on the UITableView row, the keyboard dismisses, but the didSelectRow method is not working. It wont push the new ViewController once clicked on the cell.

Also the other way around, once I change it, you can click on the TableView cell, the keyboard dismiss and the other ViewController is pushed, but the touch on any other place is not dismissing the keyboard.

What should I do?

- (IBAction)hideKeyboard:(id)sender
{
    [tfFoodsSearchQuery resignFirstResponder];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {

    if ([touch.view isKindOfClass:[UITableView class]])
    {
        // we touched a button, slider, or other UIControl
        return YES; // handle the touch
    }
    NSLog(@"Touch");
    return NO; // ignore the touch
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(hideKeyboard:)];

    [self.view addGestureRecognizer:tap];

    UITapGestureRecognizer *gestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard:)];
    gestureRecognizer.delegate = self;
    [self.tvFoods addGestureRecognizer:gestureRecognizer];
}

Thanks!

回答1:

set

[gestureRecognizer setCancelsTouchesInView:NO];

and instead of adding it to the tvFoods, add to entire self.view, so it won't affect overridden definitions.

also, remove the shouldReceiveTouch delegate, it is not necessary



回答2:

Using whiteagle's tip, I use the following code to trap a single tap to close the keyboard in a UITableView. It passes the tap through and still allows a row to be selected. In my case, the tap being passed through triggers an inline date picker to be displayed.

  -(void)viewDidLoad {
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)];
    [singleTap setNumberOfTapsRequired:1];
    [singleTap setNumberOfTouchesRequired:1];
    [singleTap setCancelsTouchesInView:NO];
    [self.view addGestureRecognizer:singleTap];
    singleTap = nil;
  }

  // 
   -(IBAction)hideKeyboard {
    [activeTextField resignFirstResponder];
  }