Memory Management and nil Conferences Of Interest To iPhone Developers
Feb 19

In a previous post I presented a framework for creating a data entry screen. That code focused mainly on UITextFields and allowed the user to move to the next field by tapping the Return key on the keyboard.

What if you have one or more UITextViews on your data entry screen because you want the user to be able to enter multiple lines of text? Well the UITextView handles the Return key internally and adds a new line to the text being entered, just like you would expect when you’re writing text in a text editor. And there is no equivalent of textFieldShouldReturn for UITextView.

If you don’t care about newlines in the entered text and you just want to exit the field when the Return key is tapped, then add the following method to the UITextViewDelegate:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  BOOL shouldChangeText = YES;

  if ([text isEqualToString:@"\n"]) {
    // Find the next entry field
    BOOL isLastField = YES;
    for (UIView *view in [self entryFields]) {
      if (view.tag == (textView.tag + 1)) {
        [view becomeFirstResponder];
        isLastField = NO;
        break;
      }
    }
    if (isLastField) {
      [textView resignFirstResponder];
    }

    shouldChangeText = NO;
  }

  return shouldChangeText;
} 

The shouldChangeTextInRange method is called after each keystroke is received by the UITextView, but before it’s shown on screen. If the text is a “\n” character (the Return key) then we either set first responder to the next field, or hide the keyboard in the case that this is the last field. (The entryFields method is explained in the previous post.) Return NO if a return character was detected since we don’t want the new line to show up in the UITextView, otherwise return YES and the text will be processed and shown in the UITextView as normal.

written by Nick \\ tags: ,

One Response to “Handling the Return Key in a UITextView”

  1. Frank Maroney Says:

    Thank you, very helpful!

Leave a Reply