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.
Try this scroll view delegate method -
link delegate in IB to scroll view and then cop this code (modify as per your need).
This should work. You can try other delegate methods too like
Create a extension class for hiding keyboard when touches scrollview/view anywhere
}
And call this method in viewDidLoad like
Here is the cleanest way to achieve this in iOS 7.0 and above.
Or
Swift:
Or
A bit late but if anyone else is searching an answer to this problem with Swift 3:
When I added the gesture to a subclass of
UIScrollView
, I was having problems with the various gestures in my view tree interfering with each other, such as being able to click on subviews, scroll the view, and have the keyboard dismiss in all cases. I came up with this solution, which can be setup from a superclass ofUIScrollView
or from aUIViewController
.The
DismissKeyboardTapGesture
class uses ARC, works with any text fields under the view, and doesn't take over any clicks from subviews like buttons. Also takes advantage of iOS7 scrolling effect to dismiss keyboard.Setting up from UISScrollView superclass:
or from UIViewController:
Here is the class:
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: