Undocumented feature #1: Dismissing the keyboard when the user taps the “Return” key

One of the features that was included in the app but discussed only in passing was the dismissal of the keyboard when the user tapped the Return key. While this is convenient for the user, it’s not iOS’ default behavior. You have to watch for the event where the user taps the Return key, and then respond accordingly.

The UITextFieldDelegate protocol’s textFieldShouldReturn(textField: UITextField) method is called whenever the user taps the Return key while editing a text field. It accepts a single parameter, textField, which is a reference to the text field the user was editing when s/he tapped the Return key. It returns a bool — true if the text field should implement its default behavior for the Return key; otherwise, false otherwise. It’s where you should place code to intercept the Return key event.

What should that code be? If you remember only one thing from this article, let it be this:

The way to dismiss the iOS keyboard after the user is editing a text field is to make the text field resign its role as first responder.

What’s the first responder, you ask?

The short answer is that the UI object that currently has the first responder role in iOS is roughly analogous to the UI object that currently has the focus in other systems (such as Android, HTML, and .NET).

The long answer is that the first responder is the first view in the responder chain to receive many events. Most of the time, it’s the view in a window that an app deems best suited for handling an event. You can find out more by reading these Apple documents: Event Delivery: The Responder Chain and their Responder object documentation.

Take a look at code in the example app in my earlier article, particularly ViewController.swift.

All this setup means that whenever the user edits any of the text fields in the view — whether it’s vowelsOnlyTextField, noVowelsTextField, digitsOnlyTextField, numericOnlyTextField, or positiveIntegersOnlyTextField — and then hits the Return key, the textFieldShouldReturn(textField: UITextField) method gets called.

It tells the text field to resign its first responder role (by invoking its resignFirstResponder() method). In this application, we want the keyboard to disappear when the user taps the Return key regardless of the text field, so we don’t bother trying to identify the text field; we simple call textField.resignFirstResponder().

Aside from dismissing the keyboard, we want the Return key to function as it normally would, so we have the method return true, which states that text field should implement its default behavior.

Link still broken.
To make AllowedCharsTextField to work, you need to remove the delegate from the uitextfield. This means that you can’t resign the first responder by tapping the Return button.
Great code, has helped me with the iPad keyboard showing special characters.