5

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 } 
2
  • yeah just use self.textview.resignFirstResponder() Commented Jul 28, 2015 at 1:06
  • @Lamar - Use it where? Commented Jul 28, 2015 at 1:11

2 Answers 2

9

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 } 
Sign up to request clarification or add additional context in comments.

2 Comments

That does not do anything. And I am using textView, not textField.
correct function declaration is func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
1

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() } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.