Hiding a Keyboard with Delegation

Another option for hiding a textField's keyboard is to have the keyboard hide when the 'Return' key is pressed.

If you want to have the keyboard hide when the return key is pressed, a few things need to be set up. The first step is setting the viewController to be the delegate for the textField, and understanding how delegation works.

NOTE

There are no equivalent delegate functions for textViews as they allow multiple lines of text when the return key is pressed. This makes the 'Return' key unusable for hiding the textView's keyboard.

Make a Class the Delegate for Another Class

A delegate is something that receives events on behalf of, and performs functions for, another thing. Because all of your code lives inside your viewController class, you will want the viewController to be the delegate for the textField object within its own view. The viewController will then be able to see the events generated by the textFields and their keyboards.

Looking at the previous lesson's code, we had the following:

Hide keyboard with delegate

First you must set your viewController to implement a UITextFieldDelegate protocol.

Hide keyboard with delegate

That will tell your ViewController that it is going to be a delegate for a UITextField, but it does not specify which one. You must manually set the textField's delegate to the viewController.

Hide keyboard with delegate

TIP

Remember that within a viewController class, the 'self' variable refers to the viewController itself.

This gives the viewController class implemented a series of methods that can perform actions when the user interacts with the textField. By implementing the textFieldShouldReturn method in your viewController class, you code what happens when the 'Return' key is pressed on the iOS keyboard. This can be used to hide the keyboard by calling the textField's resignFirstResponder() method to hide the keyboard.

Hide keyboard with delegate

Now, when you click in the textField in your application, you will be able to click the 'Return' key to hide the keyboard.

The following video describes using how to use delegation to hide the keyboard:

iOS 12 Development Essential Training - Dismiss the keyboard with delegation LinkedIn Learning

Back to Week 4

Last Updated: 9/29/2020, 5:00:23 PM