Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i dismiss the keyboard on return key from a UITextView

How do I dismiss the keyboard by pressing the return key on device? I know how to dismiss keyboard, but not when using the UITextView:

resignFirstResponder

I have tried this, but it does not work:

self.messageTextView.delegate = self

And with this function:

func messageTextViewShouldReturn(textView: UITextView) -> Bool
    {
        self.messageTextView.resignFirstResponder()
        return true
    }
like image 718
Eri-Sklii Avatar asked Jul 28 '15 00:07

Eri-Sklii


2 Answers

Remember to add the UITextDelegate into ViewDidLoad()

 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n"
    {
        textView.resignFirstResponder()
        return false
    }
    return true
}
like image 197
Lamour Avatar answered Sep 28 '22 16:09

Lamour


Swift 5

unlike a textField where IBActions are available, there are no actions available for text views.

create your textViewOutlet

If you are using a tableview: identify where your textView row is located:

let textViewIndex = IndexPath(row: 0, section: 1)

then in (_:didSelectRowAt:) dismiss the keyboard if any row other than your textView

if indexPath != textViewIndex {
                   textViewOutlet.resignFirstResponder()
               }

if you are not using a tableview: In your SB viewcontroller, drag a UITapGestureRecognizer to your view. Then create an IBAction from that Tap Gesture Recognizer by control dragging it to your view. In the action dismiss your keyboard from your textViewOutlet:

    @IBAction func tapGestureRecognizer(_ sender: Any) {
notesField.resignFirstResponder()
    }
like image 21
DIV Avatar answered Sep 28 '22 15:09

DIV