Return’s Key

Standard

Got an iOS app with several text fields? Something like this:

Screen Shot 2014-04-10 at 22.21.29

You have? Well, you can add a nice bit of polish by making the keyboard’s return button toggle between them. In this example, the return key should read “Next” for the first two fields, then “Done” for the last one.

Users can then fill in the entire screen just using the keyboard; without having to tap the correct text field each time. They’ll love and worship you, and buy you wonderful gifts. Probably.

You can set this up manually, but it’s a bit of a pain:

FirstNameField.ReturnKeyType = UIReturnKeyType.Next;
FirstNameField.ShouldReturn = (textField) =>
{
    MiddleNameField.BecomeFirstResponder();
    return true;
};

MiddleNameField.ReturnKeyType = UIReturnKeyType.Next;
MiddleNameField.ShouldReturn = (textField) =>
{
    LastNameField.BecomeFirstResponder();
    return true;
};

LastNameField.ReturnKeyType = UIReturnKeyType.Done;
LastNameField.ShouldReturn = (textField) =>
{
    SubmitName();
    return true;
};

Dull, Boring and Repetitive. Everything code shouldn’t be.

How about doing this instead?

this.SetupFieldOrder(new [] { FirstNameField, MiddleNameField, LastNameField }, SubmitName);

Stick TextFieldOrderExtension.cs in your project, and you can.

Call it from ViewDidLoad in a UIViewController. The method takes two arguments:

  1. An array of UITextField objects, in the order they should be filled out
  2. An Action to be called when return is tapped on the final text field (optional)

If you leave out the second argument, it’ll just loop back round to the first text field. It even sorts out the return key to read the appropriate action: “next” or “done”.

There’s also an example project on Github.

Leave a Reply