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

主宰稳场 提交于 2019-12-06 12:02:44

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.

The culprit is [textView resignFirstResponder];.

Do you really need - textView:shouldChangeTextInRange:replacementText:? If not, just delete the whole method, going to next line is the default behaviour of pressing the "done"(it's "return" by default) key and it has been modified by [textView resignFirstResponder]; in - textView:shouldChangeTextInRange:replacementText:. If you do, at least you need to delete [textView resignFirstResponder]; to avoid your description.

swift 3 , 4

 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if text == text.trimmingCharacters(in: .newlines) {
            return true;
        }else{
            textView.resignFirstResponder()
            return false
        }
    }
RJ raj

Insert new line by tapping the return key in UITextView ios

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if textView == textViewForChat
    {


        if (text == "\n")
        {
            textView.text = textView.text + "\n"
            //textView.resignFirstResponder()

         }

     }
return true
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!