how to add an action on UITextField return key?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
On iOS, pressing the return key in a UITextField usually means one of three things: submit the value, move to the next field, or dismiss the keyboard. The standard way to handle that action is through the UITextFieldDelegate, though target-action also works for simpler cases.
The Delegate Method You Usually Want
UITextFieldDelegate includes textFieldShouldReturn(_:), which is called when the user taps the return key.
Returning true allows the text field to process the return normally. Calling resignFirstResponder() dismisses the keyboard.
Moving to the Next Field
In forms, the return key often advances the user to another input rather than closing the keyboard.
This pattern is common because it makes the keyboard behave like a natural part of the form flow.
Triggering a Submit Action
If the return key should submit the form, call the same method your button would use.
This keeps the form logic in one place instead of duplicating it between the button and the return-key path.
Using Target-Action Instead
For simpler cases, you can respond to .editingDidEndOnExit, which fires when the return key ends editing.
This is fine for one field, but the delegate approach scales better when you have several text fields or more nuanced behavior.
Configure the Return Key Type
The label on the key should match the action you expect.
Useful return key types include:
- '
.done' - '
.next' - '
.go' - '
.search' - '
.send'
This does not change the logic automatically, but it gives the user a better cue.
A Practical Form Pattern
In a real form, you usually combine three behaviors:
- assign the delegate
- set a sensible return key type
- move focus or submit based on which field is active
That creates predictable keyboard behavior without extra gesture code or button-only flows.
Common Pitfalls
The biggest pitfall is forgetting to set the text field's delegate. If the delegate is not assigned, textFieldShouldReturn(_:) will never be called.
Another issue is dismissing the keyboard without handling the actual intended action. If the return key is supposed to submit or advance focus, make that explicit.
Developers also duplicate form-submission logic inside both the delegate method and a button action. It is cleaner to route both through one shared method.
Finally, make sure the chosen returnKeyType matches the action. A key labeled .done that silently moves to the next field is a poor UI signal.
Summary
- Use
textFieldShouldReturn(_:)for the standard return-key action. - Assign the text field's delegate or the method will not fire.
- Use the return key to dismiss the keyboard, move to the next field, or submit the form.
- '
editingDidEndOnExitis a valid target-action alternative for simpler cases.' - Match
returnKeyTypeto the actual user action for better UX.

