Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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
    }
}

To have the done button dismiss the keyboard and resignFirstResponder you have to implement a delegate method.

  1. In your .h implement the UITextFieldDelegate

    @interface YourViewController : UIViewController <UITextFieldDelegate>
    
  2. Then implement the textFieldShouldReturn in your .m

    -(BOOL) textFieldShouldReturn:(UITextField *)textField
    {
    [textField resignFirstResponder];
    return YES;
    }
    
  3. Don't forget to link the delegate of UITextField to the file's Owner (very important)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top