2

I am new in iOS development. I want to hide the keyboard when tapping outside of a UITextView. My TextView is in a cell from an UITableView. The problem is that I have a Toolbar at the top and my buttons doesn't react anymore. I implemented the method "shouldReceiveTouch" but my test is not correct i think. Any ideas? Thank you and sorry for my bad english..

In my ViewDidLoad:

tap = [[UITapGestureRecognizer alloc]
                               initWithTarget:self
                               action:@selector(dismissKeyboard)];
tap.delegate = self;
[self.view addGestureRecognizer:tap];

note: tap is an UITapGestureRecognizer property.

Implemented methods:

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

    if ([touch.view isKindOfClass:[UIBarButtonItem class]]) {
        return NO;
    }
    return YES;
}

-(void)dismissKeyboard {
    [tview resignFirstResponder];
}
beny1700
  • 284
  • 1
  • 4
  • 10

4 Answers4

1

UIBarButtonItem is not a subclass of UIView, hence the shouldReceiveTouch still return YES.

Try to exclude the whole UIToolbar or just add the tap gesture recognizer in the UITableViewCell when you initialize the cell in cellForRowAtIndexPath.

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

    if ([touch.view isKindOfClass:[UIToolbar class]]) {
        return NO;
    }
    return YES;
}
Valent Richie
  • 5,226
  • 1
  • 20
  • 21
0

use didScroll method of UIScrollView delegate to resign keyboard.TableView is also subclass of UIScrollView so it should work.

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
     [tview resignFirstResponder];
}

or use this one

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
  [tview resignFirstResponder];
}

If you still want to use gesture then add gesture to UIView or self.view or superView of tableView instead of adding it to tableView

Try following code :----

Keep you code as it is and add this method

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
     [tview resignFirstResponder];
}
Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
0

You should add your gesture to table view.

 tap = [[UITapGestureRecognizer alloc]
                                   initWithTarget:self
                                   action:@selector(dismissKeyboard)];
    tap.delegate = self;
    [tblView addGestureRecognizer:tap];
Dharmbir Singh
  • 17,485
  • 5
  • 50
  • 66
0

in viewDidLoad set self.view.userInteractionEnabled = yes;

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

UITouch *touch = [[event allTouches] anyObject];

if ([touch view] == tview) {

    [tview resignFirstResponder];

}

}
MobileMon
  • 8,341
  • 5
  • 56
  • 75