1

I have a UITextField in my iOS app. When a user enters text and clicks Return, the keyboard goes away due to a call to an IBAction with "resignFirstResponder."

However, XCode does not let me drag a line from the UIView itself to File Owner. How do I associate touching the background of a UIView with an IBAction that makes the keyboard go away?

Justin Copeland
  • 1,891
  • 5
  • 23
  • 27

4 Answers4

10

You can use UITapGestureRecognizer. see: Dismiss keyboard by touching background of UITableView

so instead of tableview, just add it to your view instead:

UITapGestureRecognizer *gestureRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)] autorelease];
gestureRecognizer.cancelsTouchesInView = NO; //so that action such as clear text field button can be pressed
[self.view addGestureRecognizer:gestureRecognizer];

and have a method to hide your keyboard

- (void) hideKeyboard {
    [self.view endEditing:YES];
}
Community
  • 1
  • 1
code007
  • 2,306
  • 2
  • 19
  • 26
1

You've already noticed that you can't drag from the UIView to the file's owner to assoctiate an action with a touch.

The way to work around this is to change the class of the background view from UIView to UIControl and hook up an action from there to a method in your controller to stop editing.

That's because a UIControl can respond to touch events, and a UIView does not, but a UIControl subclasses UIView, and so it can be used in place of a UIView.

I wrote an example project a while ago that uses this technique. Have a look at the secondViewController's xib file and see how I've change the class of the background view and hooked it up to a an action in the controller to dismiss the keyboard.

Abizern
  • 146,289
  • 39
  • 203
  • 257
0

Use the touchesBegan with Event and end editing on the view:

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

  [self.view endEditing:YES];

  }
James A Mohler
  • 11,060
  • 15
  • 46
  • 72
Richard Shergold
  • 572
  • 1
  • 8
  • 21
-1

One easy way to do it is to create a big transparent UIButton behind the view.

Eduardo
  • 1,383
  • 8
  • 13