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 id
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[self.TextField resignFirstResponder];
return YES;
}
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(TapTodissmiss)];
[self.view addGestureRecognizer:tap];
and selector
-(void)TapTodissmiss{
[self.txtffld resignFirstResponder];
}
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];
}
For my implementation, [self.view endEditing:YES] did not work.
To finally make sure the keyboard was hidden, I had to make one of my views the first responder, and then immediately make it resign as per the function below:
-(void) hideKeyboardPlease{
[uiTextTo becomeFirstResponder];
[uiTextTo resignFirstResponder];
}
This is the easiest way iv found that works consistently. Just add a tap gesture recognizer on the view and you're good to go.
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
[self.view endEditing:YES];
}
UIViewController
inherits from UIResponder
so a naive way (I am pretty sure is not the smartest way to do it) would be by overwriting the following methods (at least 1 of them)
– touchesBegan:withEvent:
– touchesMoved:withEvent:
– touchesEnded:withEvent:
- touchesCancelled:withEvent:
Next you could get the touched view by doing
UITouch *touch = [touches anyObject];
UIView *touchedView = [touch view];
finally resign the first responder if that view is not your text field
if(touchedView != textField){
[textField resignFirstResponder];
}
_
Demerits of this approach:
You will have to handle the "tap" by yourself. (Same problem as the old iOS 3.1 or earlier). You will have to come up with your own implementation to differentiate single taps from drags, swipes, double taps, long taps, etc. Is not hard to get it working well but it is not likely you get it exactly the same way Apple detects taps (timings, distances, thresholds count!) However, that depends on your needs.
If your view structure is simple enough then you could add a gesture recognizer to the container view and resign the first responder every time the handler is called :)
Hope this helps