Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dismiss keyboard for UITextView with return key?

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?

like image 642
Chilly Zhong Avatar asked Apr 01 '09 01:04

Chilly Zhong


People also ask

How do you dismiss a keyboard?

Android devices have a solution; press the physical back button (provided on some mobile phones) or the soft key back button, and it closes the keyboard.

How to dismiss the keyboard in swift?

Via Tap Gesture This is the quickest way to implement keyboard dismissal. Just set a Tap gesture on the main View and hook that gesture with a function which calls view. endEditing . Causes the view (or one of its embedded text fields) to resign the first responder status.


2 Answers

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 } 
like image 73
samvermette Avatar answered Sep 16 '22 12:09

samvermette


UITextView does not have any methods which will be called when the user hits the return key. If you want the user to be able to add only one line of text, use a UITextField. Hitting the return and hiding the keyboard for a UITextView does not follow the interface guidelines.

Even then if you want to do this, implement the textView:shouldChangeTextInRange:replacementText: method of UITextViewDelegate and in that check if the replacement text is \n, hide the keyboard.

There might be other ways but I am not aware of any.

like image 32
lostInTransit Avatar answered Sep 19 '22 12:09

lostInTransit