praks5432
praks5432

Reputation: 7792

Background tap on table view

So this is what my view looks like - there's a text field on top acting as a search bar, and then below that there is a table view. I want to implement backgroundTap, so that when I tap anywhere the keyboard goes away if it is up.

I've tried doing this by changing the view to be a UIControl and adding this -

- (IBAction)backgroundTap:(id)sender{
NSLog(@"BACKGROUND TAPPED");
[self.searchBar resignFirstResponder];

}

This doesn't work - the backgroundTap method doesn't run when I click on the tableView (and I've connected things properly).

I also tried overriding the touchesBegan method for the table view, but that didn't work either.

How do I achieve what I'm trying to achieve?

EDIT-

I tried to do this-

  tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(backgroundTap:)];
     tapRecognizer.numberOfTapsRequired = 1;
     [self.view addGestureRecognizer:tapRecognizer];
     tapRecognizer.enabled = NO;

Upvotes: 1

Views: 239

Answers (2)

TotoroTotoro
TotoroTotoro

Reputation: 17622

Solution 1

When your search bar becomes a first responder (starts accepting keyboard input), create a new view and place it on top of your table view. Make it transparent, and add a tap gesture recognizer to it. In the tap handler, call [self.searchBar resignFirstResponder], and remove or hide this transparent view.

Here's how you can create this overlay view:

// declare overlayView as a property or an ivar
_overlayView = [[UIView alloc] initWithFrame:self.tableView.frame]; 
_overlayView.alpha = 0; // make transparent 
[self.view insertSubview:_overlayView aboveSubview:self.tableView];

Solution 2

You can resign first responder inside the UITableViewDelegate method tableView:didSelectRowAtIndexPath: This way a single tap will dismiss the keyboard, and also trigger whatever action you've programmed for tapping on cells.

Upvotes: 1

JustAnotherCoder
JustAnotherCoder

Reputation: 2575

You want to use UITapGestureRecognizer.

In your .h file:

@interface viewController: UIViewController <UITextFieldDelegate>
{
    UITapGestureRecognizer *tapRecognizer;
}

In your your .m file:

 - (void)viewDidLoad {
     yourTextField.delegate = self;

     tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
     tapRecognizer.numberOfTapsRequired = 1;
     [self.view addGestureRecognizer:tapRecognizer];
     tapRecognizer.enabled = NO;

 }

 -(void)tapDetected {
     [yourTextField resignFirstResponder];
 }

Upvotes: 0

Related Questions