beny1700
beny1700

Reputation: 274

IOS: hide keyboard on touch UITableView

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

Upvotes: 2

Views: 3418

Answers (4)

Valent Richie
Valent Richie

Reputation: 5226

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

Upvotes: 1

MobileMon
MobileMon

Reputation: 8651

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

}

}

Upvotes: 0

Prince Kumar Sharma
Prince Kumar Sharma

Reputation: 12641

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

Upvotes: 0

Dharmbir Singh
Dharmbir Singh

Reputation: 17535

You should add your gesture to table view.

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

Upvotes: 0

Related Questions