Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resign first responder from text field when user tap elsewhere?

I have filled my view with ScrollView (same size as the view) and I'm stuck at how to resign first responder when user tap elsewhere in the View (or the scrollview). Any idea on how to do that ? I'm using the following method but it's not working as expected:

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

Thx for helping,

Stephane

like image 773
Steve Avatar asked Oct 17 '11 14:10

Steve


4 Answers

I found the answer here:

If your ultimate aim is just to resign the first responder, this should work: [self.view endEditing:YES]

The endEditing(_:) method is designed right for it

Causes the view (or one of its embedded text fields) to resign the first responder status.

like image 162
DanSkeel Avatar answered Oct 12 '22 19:10

DanSkeel


For a more robust and clean solution add a tap gesture recognizer to your primary view.

This will work better with nested views and will be cleaner than secret buttons in code and UI builder.

In your view did load:

UITapGestureRecognizer* tapBackground = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)]; [tapBackground setNumberOfTapsRequired:1]; [self.view addGestureRecognizer:tapBackground]; 

..and define your target action to be triggered on tap:

-(void) dismissKeyboard:(id)sender {     [self.view endEditing:YES]; } 
like image 37
Andres Canella Avatar answered Oct 12 '22 19:10

Andres Canella


The best option is the shortest way ;)

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
like image 32
Onder OZCAN Avatar answered Oct 12 '22 20:10

Onder OZCAN


Using Swift you can do this:

func viewDidLoad() {
    super.viewDidLoad()

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.hideKeyboardByTappingOutside))
    
    self.view.addGestureRecognizer(tap)
}

@objc func hideKeyboardByTappingOutside() {
    self.view.endEditing(true)
}
like image 34
pableiros Avatar answered Oct 12 '22 19:10

pableiros