How to create a new line by tapping the return key in UITextView ios

user2786 picture user2786 · Apr 12, 2015 · Viewed 11.4k times · Source

I am newly to iPhone. I have added one UITextView using XIB in my application, now after tapping on done key it's simply resigning the keyboard. But, I want to create a new line by tapping it, means it should go to the next paragraph. Please help me to achieve my output. Here is my code :

- (void)textViewDidEndEditing:(UITextView *)textView1
{
    if (![textView1 hasText]) {
        [textView1 addSubview:placeholderLabel];
    }
    else{
        NSLog(@"done button clicked!!");
    }

    CGRect rect;

    if(screenBounds.size.height == 568)//iPhone5
    {
        rect = CGRectMake(5, 76, 310, 491);
    }
    else{
        if(_kisiOS7){
            rect = CGRectMake(5, 76, 310, 404);
        }
        else{
            rect = CGRectMake(0, 44, 320, 436);
        }
    }

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.3];

    txtView.frame = rect;

    [UIView commitAnimations];
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.length == 0) {
        if ([text isEqualToString:@"\n"]) {
            [textView resignFirstResponder];
            return NO;
        }
    }

    return YES;
}

Thanks in advance.

Answer

sfirite picture sfirite · Apr 12, 2015

You should implement delegate method with returning value NO (so on tapping "return" or "done" it will not close keyboard).

- (BOOL)textViewShouldEndEditing:(UITextView *)textView {
    return NO;
}

and remove or change logic of next lines of code:

if (range.length == 0) {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
}

So in textViewShouldEndEditing you can determine/calculate situations when you need to close keyboard (if you want to close - return YES, otherwise return - NO)

You can also change logic of

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

to

if (range.length == 0) {
    if ([text isEqualToString:@"\n"]) {
        textView.text = [NSString stringWithFormat:@"%@\n\t",textView.text];
        return NO;
    }
}

In this case when user will tap on action button on keyboard (like "return"). Textview will insert new line and additional tab in text.

I hope it will help you.