I was thinking to discuss all possible ways to dismiss the keyboard in iOS app and figure out which one is best suited one.
UITextFields has keyboard as there first responders, as soon you begin editing keyboard shows up. It is developer’s responsibility to write code to dismiss it. Let me explain few methods how to do it especially when there are multiple UITextFields on your view controller.
First way: Implement textFieldShouldReturn delegate in the view controller and dismiss current keyboard.
Third: what could be better than tapping anywhere on the view controller to dismiss the keyboard. Just one line of code would serve our purpose. Add a tap gesture recogniser on self.view, set target as self.view and set selector as endEditing: (in ViewDidLoad() or anywhere you like)
As Uncle Ben said “Great power comes with great responsibility”, there could be issues if you are dealing with Table Views and adding above tap gesture. You might get issues while selecting the rows, didSelectRowAtIndex path could not be fired until pressed long.
so there is solution for that. Modify above code as below.
let tap = UITapGestureRecognizer(target: self.view, action: Selector(“endEditing:”)) tap.cancelsTouchesInView = false self.view.addGestureRecognizer(tap)
Just make sure cancelsTouchesInView is set false.
Fourth: If your textfields are added on UIScrollview or any subview of it eg. UITableView, you can use set `keyboard dismiss mode` like below.
this will do all stuff for you without writing any extracode