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
}
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
}
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()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With