Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismissing the keyboard in a UIScrollView

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.

like image 825
Nicholas1024 Avatar asked Feb 28 '11 15:02

Nicholas1024


People also ask

How do you dismiss a keyboard from the tap?

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.

How do you dismiss a keyboard in Swift?

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.


Video Answer


2 Answers

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 
like image 134
Pei Avatar answered Sep 19 '22 09:09

Pei


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]; } 
like image 22
Zhang Avatar answered Sep 23 '22 09:09

Zhang