Keyboard dismiss and UITableView touch issue

↘锁芯ラ 提交于 2019-12-08 09:54:52

问题


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


来源:https://stackoverflow.com/questions/13109282/keyboard-dismiss-and-uitableview-touch-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!