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
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.
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]; }
The best option is the shortest way ;)
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With