How to make UITextView "Done" button resignFirstResponder?

33,488

Solution 1

new Answer

On your View, you'd have a UIBarButton ("Done") that is connected to the IBAction below:

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

Where textView is your textView outlet defined in your .h file and connected in Storyboard or .xib file. Like this:

@property (retain, nonatomic) IBOutlet UITextView *textView;

old Answer

Check the following:

  1. Is UITextViewDelegate specified in .h
  2. Implement delegate method for uitextview: textViewShouldEndEditing, return YES
  3. make sure your .m (controller) is the delegate for uitextview in IB
  4. resignFirstResponder should now work.

Solution 2

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.

Solution 3

You can implement UITextViewDelegate and wait for "\n", in Swift 4 :

    myTextView.delegate = self

// ...

extension MyViewController : UITextViewDelegate {

    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == "\n" {
            textView.resignFirstResponder()
            return false
        }

        return true
    }
}
Share:
33,488
Jason
Author by

Jason

Updated on July 30, 2022

Comments

  • Jason
    Jason almost 2 years

    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?