Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextView resign first responder on 'Done'

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?

like image 991
Richard J. Ross III Avatar asked Jun 20 '11 13:06

Richard J. Ross III


1 Answers

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;
    }
like image 160
Jhaliya - Praveen Sharma Avatar answered Oct 06 '22 00:10

Jhaliya - Praveen Sharma