I have a UITableView
with UITextField
s as cells. I would like to dismiss the keyboard when the background of the UITableView
is touched. I'm trying to do this by creating a UIButton
the size of the UITableView
and placing it behind the UITableView
. The only problem is the UIButton
is catching all the touches even when the touch is on the UITableView. What am I doing wrong?
Thanks!
Here's how I finally made works. I combined suggestions and codes from different answers. Features: dismissing keyboard, moving text fields above keyboard while editing and setting "Next" and "Done" keyboard return type.REPLACE "..." with more fields
I had a
UITableViewController
and implementingtouchesBegan:withEvent:
didn't work for me.Here's what worked:
Swift:
Objective-C:
I wanted my cell to open the keyboard when any part of the cell was selected and close it if you clicked anywhere off the cell. To open the keyboard:
(NOTE: I've subclassed the cell but you can easily achieve this in the
tableView:didSelectRowAtIndexPath:
delegate method ofUITableView
)Doing this meant that with the top solutions if you clicking on the cell twice the keyboard would shake as, first the gesture recogniser tried to close the keyboard, and second the cell was reselected and tried open the keyboard.
Solution is to check whether the click occurred inside the currently selected cell:
Here's the swift version for your coding pleasure:
It adds a tap gesture recognizer then dismisses the keyboard. No outlet for the TextField is required!
I've found a solution that works great.
Is needed to use the UIGestureRecognizerDelegate and the method – gestureRecognizer:shouldReceiveTouch:.
Add the gesture recognizer to the TableView as follows:
Then, implement the shouldReceiveTouch delegate method to reject touches that are performed in UITableViewCell class. The hideKeyboard method only will be called when the touch has been performed outside UITableViewCell class.