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 14,500+ Swift developers and enthusiasts who get my weekly updates.

  • John

    Hi Natasha,

    I have recently been accepted into Dev Bootcamp, but I am also very interested in Mobile Makers. I am a solid novice/weak beginner programmer. I would love to do both, but if I had to choose 1, which would you recommend? (obviously a lot of variables involved, but answer as best as you can)

    • Hi John,

      I’m a bit biased, because I’m going to Mobile Makers after almost 2 years of experience in web development, so I really LOVE it. It’s hard for me to imagine which program would be better for beginners. If you email me at natasha [at], I can send you some intros to people are doing Mobile Makers without much prior experience.

      iOS definitely has much harder concepts in it, so I imagine that’s really hard, especially if you’re just trying to grasp the basics. Web Development, on the other hand, has a lot more components – you need to learn Ruby, Ruby on Rails, JavaScript, CSS, HTML, Databases, etc…

      Keep in mind that the two are not mutually exclusive. You need to know both web development and iOS in today’s world. So if you learn one at first, you’d be able to learn the other later. Maybe just pick the one you want to start with…