Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make UITextView "Done" button resignFirstResponder?

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?

like image 385
Jason Avatar asked Oct 20 '10 10:10

Jason


3 Answers

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.

like image 131
Rich Lowenberg Avatar answered Nov 20 '22 14:11

Rich Lowenberg


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.
like image 44
Jordan Avatar answered Nov 20 '22 13:11

Jordan


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
    }
}
like image 38
Axel Guilmin Avatar answered Nov 20 '22 13:11

Axel Guilmin