Done key in iPhone app that closes keyboard (with UITextView)
Asked Answered
N

3

14

I'm working on an iPhone app and in the iPhone app the user is typing in an UITextView. I was wondering how I could add the done key on the keyboard instead of having the normal return key and when you click on that key the keyboard closes.

Thanks!

Nader answered 15/1, 2011 at 20:25 Comment(0)
P
33

There is no -textViewShouldReturn: method in the UITextViewDelegate protocol. If you want the return (done) key to dismiss the keyboard, it's probably best to use a UITextField instead, UITextView is intended for editing multiple lines of text (so you need a way to enter a linebreak).

If you really want to dismiss the keyboard when hitting the return key in a UITextView, you could probably do something like this:

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  if ([text isEqual:@"\n"]) {
    [textView resignFirstResponder];
    return NO;
  }
  return YES;
}
Pediculosis answered 15/1, 2011 at 21:19 Comment(1)
Thanks! The reason I was in need of using a TextView is because the app I'm working on is a Twitter API. And if the user would like to read thru the tweet before posting it then that would be a little messier for the user.Nader
P
-4

It's as simple as:

textField.returnKeyType=UIReturnKeyDone;

Add this to your text field's delegate to remove the keyboard when it's pressed:

- (BOOL)textFieldShouldReturn:(UITextField *)aTextfield {
    [aTextfield resignFirstResponder];
    return YES;
}
Pursuer answered 15/1, 2011 at 20:49 Comment(6)
Yeah but that doesn't close the keyboard.Nader
Sorry about that. Added it to my answer.Pursuer
I think the question was referring to UITextView not UITextFieldHypertrophy
This isn't answering the question. The question is about UITextView which does not have the delegate method textFieldShouldReturn.Auten
questioner expected the answer about UITextViewTetravalent
Thanks, this really helped me as my textFieldShouldEndEditing and textFieldDidEndEditing delegate functions were not being called.Anastase
H
-6

In addition to setting:

textField.returnKeyType = UIReturnKeyDone;

you need to set the text field's delegate to your class, and do something like this:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];

    return YES;
}

This setting the returnKeyType can be done from Interface Builder as well - if you have your UI defined in a XIB. On the other hand the -resignFirstResponder will make sure that the keyboard disappears. It should be done in the -textFieldShouldReturn: delegate method, since that is invoked when the user taps on the Done button.

Hope this helps.

Hungary answered 15/1, 2011 at 20:57 Comment(2)
He asks for UITextView not UITextField.Ionize
Also not answering the question.. the question is about UITextView.Auten

© 2022 - 2024 — McMap. All rights reserved.