Alright, I have a couple of UITextFields
and UITextViews
inside a UIScrollView
, and I'd like to set the keyboard to disappear whenever the scrollview
is touched or scrolled (except when you touch down inside the text field/view, of course).
My current attempt at doing this is replacing the UIScrollView
with a subclass, and setting it to call a removeKeyboard function (defined inside the main view controller) inside the touchesBegan method. However, this only removes the keyboard for a normal touch, not when the view is simply scrolled. So, what's the best way to remove the keyboard inside a UIScrollView
?
Thanks in advance for your help.
Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.
Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.
Here is the cleanest way to achieve this in iOS 7.0 and above.
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
Or
scrollView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
In Swift:
scrollView.keyboardDismissMode = .onDrag
Or
scrollView.keyboardDismissMode = .interactive
Bit late but if anyone else is searching an answer to this problem, this is how I have gone about solving it:
1) Create a tap gesture recognizer with a target callback method to dismiss your keyboard using resignFirstResponder on all your fields.
2) Add the tap gesture to the scrollview.
Here's an example:
UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyboard)]; // prevents the scroll view from swallowing up the touch event of child buttons tapGesture.cancelsTouchesInView = NO; [pageScrollView addGestureRecognizer:tapGesture]; [tapGesture release]; ... // method to hide keyboard when user taps on a scrollview -(void)hideKeyboard { [myTextFieldInScrollView resignFirstResponder]; }
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