touchesBegan not getting called

3.1k views Asked by At

I have a few UITextFields in static UITableVieweCells, and I'm trying to dismiss keyboard when the user taps elsewhere. Here is my code:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
   [self.view endEditing:YES];
    NSLog(@"touch began");
}

I didn't get any NSLogs when I taped elsewhere. What am I doing wrong?`

I then tried self.view.userInteractionEnabled = YES;, and self.tableView, and they both didn't work.

2

There are 2 answers

1
Patrick Lynch On BEST ANSWER

Your touches are probably being swallowed by the table view cells. Try putting your keyboard dismiss code in tableView:didSelectRowAtIndexPath: on your table view delegate instead.

EDIT:

Perhaps then you ought to use some combination of that and gesture recognizers:

UITapGestureRecognizer *navBarTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[self.navigationController.navigationBar addGestureRecognizer:navBarTap];

UITapGestureRecognizer *tableViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[self.tableView addGestureRecognizer:tableViewTap];
0
Akshay Karanth On

Touchesbegan is not called in UIScrollview and UITableview is a subclass of uiScrollview so make subClass of your UITableview and implement all

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

// If not dragging, send event to next responder
  if (!self.dragging){ 
    [self.nextResponder touchesBegan: touches withEvent:event]; 
  }
  else{
    [super touchesEnded: touches withEvent: event];
  }
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

// If not dragging, send event to next responder
    if (!self.dragging){ 
     [self.nextResponder touchesBegan: touches withEvent:event]; 
   }
   else{
     [super touchesEnded: touches withEvent: event];
   }
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{

  // If not dragging, send event to next responder
   if (!self.dragging){ 
     [self.nextResponder touchesBegan: touches withEvent:event]; 
   }
   else{
     [super touchesEnded: touches withEvent: event];
   }
}