6 Mar 2014

iPhone Development: Resign or dismiss keyboard when return key pressed in UITextView

UITextview is a common UI(User interface) control used in iPhone app development as it allows user to write down long content. One of the most common problem faced by iPhone app developers is to dismiss the keyboard when user press return key on keyboard. All developers are familiar with resignFirstResponder method to dismiss keyboard.

But in case of UITextView when user press return key on keyboard, instead of dismissing keyboard UITextView enters a new line.So what to do, in this case. You will have two methods to dismiss keyboard

1) Either allow user to dismiss keyboard by displaying him UIToolbar on top of keyboard with Done button while interacting with UITextView. So, when user hit done button you can use resignFirstResponder method to dismiss keyboard. Code for dismissing keyboard is shown below

        [textView resignFirstResponder];

2) If you don't want to go with alternate 1, then you can dismiss keyboard via checking \n character appended into string or textview text when user hit return button on keyboard. For this purpose, we will use - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text delegate method of UITextView.

Code for dismissing keyboard when user press return button is shown below

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
    if ([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
        return NO;
    return YES;


NOTE:- If you use second alternate then user will not able to add text in newline while hitting return key of keyboard. 

No comments:

Post a Comment