2
votes

I have created in storyboard simple app (only one controller), I put scrollview and inside scrollview couple UITextFileds. Inside controller I have added function like

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.name resignFirstResponder];
    [self.number resignFirstResponder];

    // I have tried with and without this line but doesn't work
    [self.scrollView resignFirstResponder];
}

(name, number are Outlets of UITextField, scrollView is Outlet of UIScrollView). When I click on any of those text fields keyboard pops up but when I finish typing I cannot hide keyboard. (In previous version I didn't have scrollview and keyboard hides when I click out the text field). How to make to keyboard has behavior like in default apps, how to hide ?

2
you can use UIKeyBoardScrollView for hide your keyboard after typingSudha Tiwari

2 Answers

3
votes

I'm assuming you want to just be able to tap away from the keyboard and have it dismissed right? Just do this:

 UITapGestureRecognizer *myTapz = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userTapped)];
    myTapz.numberOfTapsRequired=1;
    myTapz.cancelsTouchesInView=NO;
    [self.view addGestureRecognizer:myTapz];//or do self.WhateverYourOtherViewIsCalled..tableview? scrollView?
    [myTapz release];

And then in your selector:

-(IBAction)userTapped
{
  [whateverYourTextFieldIsCalled resignFirstResponder];
}
2
votes

In your view controller:

[self.view endEditing:YES];

This will dismiss the keyboard no matter what field is the first responder. I think there are some exceptions, but for what you're doing it should work fine.

Also touchesBegan is a UIView method, not a UIViewController method. If you're putting it inside your UIScrollView, the scroll view's panGestureRecognizer is going to prevent touchesBegan from being called. Also when overriding touchesBegan, or other touches methods, you typically want to call super as well.

ttarules's suggestion for creating a gesture recognizer is the best way for detecting touches. You can use touchesBegan inside the view, just know that other gesture recognizers can prevent it from being called (see Session 121 - Advanced Gesture Recognition from WWDC 2010).

endEditing is the best way to dismiss the keyboard because it works even after you add other fields.