How to dismiss keyboard for UITextView with return key?

Chilly Zhong picture Chilly Zhong · Apr 1, 2009 · Viewed 308.3k times · Source

In IB's library, the introduction tells us that when the return key is pressed, the keyboard for UITextView will disappear. But actually the return key can only act as '\n'.

I can add a button and use [txtView resignFirstResponder] to hide the keyboard.

But is there a way to add the action for the return key in keyboard so that I needn't add UIButton?

Answer

samvermette picture samvermette · May 21, 2010

Figured I would post the snippet right here instead:

Make sure you declare support for the UITextViewDelegate protocol.

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

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

    return YES;
}

Swift 4.0 update:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}