12

I have been searching around the web for about an hour now, and cannot find any code to help me with this.

I have a UITextView that I need to resign first responder of when the user presses the 'Done' button on their keyboard.

I have seen code floating around the internet like this:

-(BOOL) textFieldShouldReturn:(UITextField *)textField {
 [textField resignFirstResponder];
 return NO;
}

But that will not work for a UITextView. Simply put, How can I tell when the user presses the done button on the keyboard?

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201

2 Answers2

47

Implement the shouldChangeTextInRange: delegate method.

Use below approach and the solution work only with @"\n" (new line character).

//In you *.h file make sure you add
@interface v1ViewController : UIViewController <UITextViewDelegate>

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

    myTextField.delegate = self;
}

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range 
          replacementText:(NSString *)text
        {

            if ([text isEqualToString:@"\n"]) {

                [textView resignFirstResponder];
                // Return FALSE so that the final '\n' character doesn't get added
                return NO;
            }
            // For any other character return TRUE so that the text gets added to the view
            return YES;
    }
Sam B
  • 27,273
  • 15
  • 84
  • 121
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
-4

You can use the delegate method

- (void)textViewDidEndEditing:(UITextView *)textView { 
    [textView resignFirstResponder];
}

You have to set your controller as the delegate for the TextView. For more methods you can have a look here: http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITextViewDelegate_Protocol/Reference/UITextViewDelegate.html%23//apple_ref/doc/uid/TP40006897

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
Pierre
  • 2,019
  • 14
  • 12
  • Did not work, Nothing different happened in my application. I have my delegate set up, and I have the keyboard setup the way I want it, but That code never gets called. – Richard J. Ross III Jun 20 '11 at 13:36
  • 2
    `textViewDidEndEditing:` is called when edition finished, in other words when the textView already resigned the first responder so `[textView resignFirstResponder];` inside of it won't have any effect. – nacho4d Jun 20 '11 at 13:37