iOS: How To Submit Text From A Text Field Using Just The Return Key

I was working on a simple challenge today at Mobile Makers. We were basically adding some text to a text field, clicking an “Add Button” and showing the text in a text view (see below):

However, one thing that kept annoying me over and over again was that I could not just click “Return” on my keyboard to get the field added without pressing the “Add” button. So I looked around for a simple way to do this:

First, make your ViewController a UITextFieldDelegate:

// ViewController.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITextFieldDelegate>


Now, in your ViewController.m file, delegate your text field in the viewDidLoad method:

- (void)viewDidLoad
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    self.textField.delegate = self;

Finally, implement the code you want implemented when the user clicks the return button on the keyboard. Mine was as follows (I was basically adding the new string to an array of strings and then printing out the array as a string to the textView):

- (BOOL)textFieldShouldReturn:(UITextField *)textField
    [textField resignFirstResponder];
    [self.listOfStrings addObject:self.textField.text];
    [self displayArrayAsString];
    self.textField.text = @"";
    return YES;

Of course, now that I think about it, my problem was really caused by using the simulator. It’s much easier to press the return key on my computer keyboard than clicking the “Add” button on an iPhone or iPad. I’ll need to experiment more with whether this interaction is really necessary on these devices!

Enjoy the article? Join over 20,000+ Swift developers and enthusiasts who get my weekly updates.