Dismissing the keyboard in a UIScrollView

Nicholas1024 picture Nicholas1024 · Feb 28, 2011 · Viewed 50.3k times · Source

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.

Answer

Pei picture Pei · Nov 18, 2013

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