1

I am running into an issue when trying to return the keyboard in my UITextView when the return button is selected.

Here is my code:

- (void)viewDidLoad { 

    self.captionArea.delegate = self 
} 

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    NSUInteger newLength = [self.captionView.text length] + [text length] - range.length;
    return (newLength > 30) ? NO : YES;

    if([text isEqualToString:@"\n"])
        [textView resignFirstResponder];
    return YES;

}

Any ideas why this is giving me issues? The view is just going to a newline, not returning.

david Turner
  • 33
  • 1
  • 6

1 Answers1

5

Most likely, your code simply never reaches the point where you ask text view to resign first responder. Try putting your resignFirstResponder method call above all return statements.

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {

    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }    

    NSUInteger newLength = [textView.text length] + [text length] - range.length;
    return (newLength > 30) ? NO : YES;
}

Also, you should think about switching to UITextField if all you're trying to make is a simple single line text field, because UITextView doesn't come with standard methods to hide the keyboard. As explained in this popular StackOverflow answer, "hitting the return and hiding the keyboard for a UITextView does not follow the interface guidelines".

The method described above is a simple hack and don't work properly if user enters the text which contains \n (newline) character.

Community
  • 1
  • 1
Rinat Khanov
  • 1,566
  • 10
  • 32
  • 1
    You should also return `NO` if you resign first responder since you don't want to bother with the length check nor do you want the newline added to the text view. – rmaddy Jul 28 '14 at 17:34
  • 1
    This code will fail is the user pastes in text that happens to include a newline. – rmaddy Jul 28 '14 at 17:35
  • One other issue (from the OP's original code). Why does this code check `self.captionView.text` instead of`textView.text`? – rmaddy Jul 28 '14 at 17:56