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
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:
..and define your target action to be triggered on tap:
I found an answer here: link
This method is designed right for it! Reference: endEditing:
Update
I found another simple way
simply declare a property :-
and a Tap Gesture Gecognizer:-
In ViewDidLoad
Implement the textfield delegate method didBeginEditing
Implement Your Tap Gesture Method (_resignTextField)
UIViewController
inherits fromUIResponder
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)Next you could get the touched view by doing
finally resign the first responder if that view is not your text field
_
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
Give a unique Tag to your UITextfield (i.e. 333), then to resign the first responder do this:
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: