if you’re creating an iOS app that requires typing text, your app will need to display the iOS virtual keyboard that slides up from the bottom of the screen. The problem with the virtual keyboard is that although it pops up automatically, you have to write code to make it go away.
There are basically four steps you need to follow to write code that makes the virtual keyboard go away. First, you’ll likely need a text field to allow the user to type text on the virtual keyboard, so you need to add the UITextFieldDelete to your class file like this in Swift:
Second, you’ll need to set the text field to the UITextFieldDelegate. You can do through the Connections Inspector on Xcode or just use code like this in Swift:
Third, you need to create a function called textFieldShouldReturn to end editing. This function hides the virtual keyboard if the user taps the Return key:
Fourth, you need to create a second function called touchesBegan to tell the text field to let the virtual keyboard disappear if the user taps anywhere away from the text field:
So if you create a simple iOS, single view app in Xcode using Swift, just place a text field on the view (user interface) and link it to your view controller file as an IBOutlet such as naming the text field “textFieldEntry”. Then your entire Swift class would look like this:
Now if the user taps the Return key on the virtual keyboard or taps away from the text field and the virtual keyboard, the virtual keyboard will tuck itself out of sight.