How to make UITextView "Done" button resignFirstResponder?

Jason picture Jason · Oct 20, 2010 · Viewed 33k times · Source

I am trying to make my editable UITextView resign the keyboard (resignFirstResponder) when the user taps "Done." Using a UITextField, I have been able to do this with the following code:

- (IBAction)doneEditing:(id)sender {
    [sender resignFirstResponder];
}

... and then to attach it to the relevant UITextField in Interface Builder to the action "Did End on Exit."

However, with a UITextView, I can't seem to access the "Did End on Exit" action. Any suggestions on how to make this happen?

Answer

Rich Lowenberg picture Rich Lowenberg · Sep 15, 2011

The accepted answer didn't work for me. Instead, the following delegate method should be invoked like this:

- (BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        return NO;
    }else{
        return YES;
    }
}

Paste that into the class that you assign to be the UITextView delegate and it'll work.