You and I are in the same boat. We want to use one of the touch responder methods:

  • touchesBegan:withEvent:
  • touchesCancelled:withEvent:
  • touchesEnded:withEvent:
  • touchesMoved:withEvent:

These may work fine, however if you decided to use a UITableViewController as your base, or and object with scrolling, these appear to swallow the event before it gets to you. This can be fixed by subclassing UITableView (for example), assigning your table to that class on the storyboard, then capturing the touch event. Dirty, but it should work.

Really what it comes down to is thinking slightly outside the box, to steer away from subclassing and keep it simple. In my situation I was looking to dismiss the keyboard when scrolling or tapping away from the first responder.

My solution for working with a UItableViewController:

1. Hook into the scroll event of the view controller

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

2. With scrolling firing that code off once, we just have to deal with taps where no scrolling occurs. In the ViewDidLoad method create a gesture recognizer:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGesture:)];
[self.tableView addGestureRecognizer:singleTap];

3. Finish it off by adding the  @selector call to singleTapGesture:

-(void)singleTapGesture:(UITapGestureRecognizer*)gesture{
[self.view endEditing:YES];
}

This code may need to be modified if you are working with a different controller or control, however this should provide a good start and I can see it working for most cases to begin with.

No Comments

There are no comments related to this article.

Leave a Reply

Your email address will not be published. Required fields are marked *